Possible Duplicate:
Scala: forward references – why does this code compile?
object Omg {
class A
class B(val a: A)
private val b = new B(a)
private val a = new A
def main(args: Array[String]) {
println(b.a)
}
}
the following code prints “null”. In java. similar construction doesn’t compile because of invalid forward reference. The question is – why does it compile well in Scala? Is that by design, described in SLS or simply bug in 2.9.1?
It’s not a bug, but a classic error when learning Scala. When the object
Omgis initialized, all values are first set to the default value (nullin this case) and then the constructor (i.e. the object body) runs.To make it work, just add the
lazykeyword in front of the declaration you are forward referencing (valueain this case):Value
awill then be initialized on demand.This construction is fast (the values are only initialized once for all application runtime) and thread-safe.