Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala and forward references [duplicate]

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?

like image 736
jdevelop Avatar asked Aug 29 '12 19:08

jdevelop


1 Answers

It's not a bug, but a classic error when learning Scala. When the object Omg is initialized, all values are first set to the default value (null in this case) and then the constructor (i.e. the object body) runs.

To make it work, just add the lazy keyword in front of the declaration you are forward referencing (value a in this case):

object Omg {    class A    class B(val a: A)    private val b = new B(a)    private lazy val a = new A    def main(args: Array[String]) {     println(b.a)   } } 

Value a will then be initialized on demand.

This construction is fast (the values are only initialized once for all application runtime) and thread-safe.

like image 151
paradigmatic Avatar answered Oct 23 '22 06:10

paradigmatic