Scala:为什么需要在声明期间为 var/val 赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17531229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Scala: Why is it necessary to assign values to a var/val during declaration
提问by Stupid.Fat.Cat
Unless I've been doing it wrong. It doesn't seem like we can do things like:
除非我一直做错了。我们似乎不能做这样的事情:
var x;
x = 1;
in Scala, but rather you have to declare and assign a value to it. Are there any reasons for why this is the case?
在 Scala 中,但您必须声明并为其分配一个值。为什么会这样?
回答by r.v
The obvious reason is to help not leave variables uninitialized. Note that in your declaration without initialization, you will also need to specify the type.
显而易见的原因是不要让变量未初始化。请注意,在没有初始化的声明中,您还需要指定类型。
var x: Type;
gives the following error:
给出以下错误:
only classes can have declared but undefined members (Note that variables need to be initialized to be defined)
只有类可以有声明但未定义的成员(注意变量需要初始化才能定义)
Actually only abstract classes can declare members without defining them. You can still get the desired behavior (variables initialized to a default value) as
实际上只有抽象类可以声明成员而不定义它们。您仍然可以获得所需的行为(变量初始化为默认值)作为
var x: Type = _
If Typeis a reference type, xwill be null. This scenario is useful, for example, in case where a factory method completes initialization of an object after object construction.
如果Type是引用类型,x则将是null. 例如,在工厂方法在对象构造后完成对象初始化的情况下,此方案很有用。

