In this code, x is null during construction:
abstract class A {
val x: String
println(s"A: x is $x")
}
class B extends A {
val x: String = "foo"
println(s"B: x is $x")
}
new B()
A: x is null
B: x is foo
It can be fixed by adding lazy to the declaration of x in B:
abstract class A {
val x: String
println(s"A: x is $x")
}
class B extends A {
lazy val x: String = "foo"
println(s"B: x is $x")
}
new B()
A: x is foo
B: x is foo
I don't understand exactly why. It's counterintuitive that making a val lazy should cause it to be initialized earlier than the corresponding non-lazy val would have been.