为什么Scala语言要求您初始化实例变量而不是依赖默认值? [英] Why does Scala language require you initialize a instance variable instead of relying on a default value?
问题描述
Scala语言要求您在使用实例变量之前对其进行初始化。但是,Scala不会为您的变量提供默认值。相反,您必须使用通配符下划线手动设置其值,该通配符下划线的作用类似于默认值,如下所示:
Scala language requires you initialize your instance variable before using it. However, Scala does not provide a default value for your variable. Instead, you have to set up its value manually by using the wildcard underscore, which acts like a default value, as follows
var name:String = _
我知道,我知道...我可以在类中定义构造函数定义,它以我们的实例变量作为参数,因此Scala不会如下所示强制其初始化
I know, i know... I can define a constructor in the class definition, which takes as parameter our instance variable, so Scala does not force its initialization as shown below
class Person(var name:String)
但是,我需要在主体中声明它,因为我需要使用Java注释, ElementType是FIELD或METHOD;也就是说,它只能应用于实例变量或在我们的类主体中声明的方法。
However, i need to declare it in the body because i need to use a Java annotation whose ElementType is FIELD or METHOD; that is, it can just be applied to either a instance variable or method declared in the body of our class.
问题:为什么Scala语言要求您初始化一个实例变量-无论是默认值_还是所需的任何东西-都在类的主体中声明而不是依赖默认值?
Question: Why does Scala language require you initialize a instance variable - be it a default value _ or whatever you want - declared in the body of a class instead of relying on a default value ?
推荐答案
将注释指定为构造函数参数时,您可以可以应用注释。另外,您可能需要使用元注释来限制将您正在使用的注释应用于哪个目标-请参见 http://www.scala-lang.org/api/2.10.2-RC2/index.html#scala.annotation.meta.package
You can apply the annotation when you specify it as a constructor argument. Also, you may need to use a meta-annotation to restrict which target the annotation you're using is applied to - see http://www.scala-lang.org/api/2.10.2-RC2/index.html#scala.annotation.meta.package
关于依赖默认值的问题尚不清楚。使用下划线进行初始化对应于将变量的值分配为null。您还在想其他什么默认值?
Your question about "relying on a default value" is somewhat unclear, though. Initialization using an underscore corresponds to assigning the value of the variable to null. What other default are you thinking of?
这篇关于为什么Scala语言要求您初始化实例变量而不是依赖默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!