Scala and forward references [duplicate]

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.

Leave a Comment