为什么下面的代码不会引发引用错误?
trait T1 {
println( " in T1: x = " + x )
val x=1
println( " in T1: x = " + x )
}
class C12 extends T1 {
println( " in C12: c = " + c )
val c="C12"
println( " in C12: c = " + c )
}
new C12
相反,x
默认为 0,c
默认为 null
。这在 scala 中是如何工作的?这些变量什么时候初始化?
最佳答案
As explained in the Scala Language Specification :
The scope of a name introduced by a declaration or definition is the whole statement sequence containing the binding. However, there is a restriction on forward references in blocks: In a statement sequence
s1…sn
making up a block, if a simple name insi
refers to an entity defined bysj
wherej≥i
, then for allsk
between and includingsi
andsj
,sk
cannot be a variable definition. Ifsk
is a value definition, it must be lazy.
特征和类体不是 block ,因此这里没有前向引用限制。
When are these variables initialized?
语句(包括 val
初始化)只是按顺序执行。
关于scala - 在特征体 Scala 中引用未初始化的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38217009/