Samar Samar - 3 months ago 11
Scala Question

Order of construction of nested objects and member variables

I create this object in REPL. And then tested its setup sequence in the attached image below. The results are confusing.

object T {
val default = A
var options = List[P]()
println(options)

sealed trait P

object A extends P {
override def toString = "A"
println(T.options)
println("A")
}

object B extends P {
override def toString = "B"
println(T.options)
println("A")
}

object C extends P {
override def toString = "C"
println(T.options)
println("A")
}
}



  1. In the first run, T, only the inner object A seems to be constructed. Why dont the object B and object C print anything??

  2. Also note that println(T.options) in the first run returns "null". Is this because first inner objects are setup and then the outer objects other members are setup?

  3. On typing T.A nothing is printed because the object is already setup.

  4. On typing T.B it setsup the B object and prints the T.options correctly i.e List() instead of null.



enter image description here

Answer

In the first run, T, only the inner object A seems to be constructed. Why dont the object B and object C print anything??

Because they aren't initialized, they're only declared. The reason A prints out is because of:

val default = A

Which causes A to initialize. The order of initialization is thus:

  1. Ts default variable causes A to initalize
  2. A initializes and prints null
  3. T now continues initialization and now sets a value to options

Any further invocation will now print the content of the list instead of null.

Also note that println(T.options) in the first run returns "null". Is this because first inner objects are setup and then the outer objects other members are setup?

That's because println(T.options) happens in As constructor, which is prior to your options initialization inside Ts constructor.

On typing T.A nothing is printed because the object is already setup.

That makes perfect sense, A doesn't anything additional that needs to be initialized.

On typing T.B it sets up the B object and prints the T.options correctly i.e List() instead of null.

That's right, because once you invoke T.B, you've already initialized the list via Ts constructor.

Comments