In my understanding,
When an object of subclass is created, the constructor of the subclass first calls the constructor of parent class. In the parent constructor, if there is a
def
that has been overridden then the overridden copy is called.
Due to all this, in the following code the 'env' variable is not set to (intuitively) the correct length of 1.
class C {
val range: Int = 10
val env = new Array[Int](range)
}
class A extends C {
override val range = 1
}
val a = new A
a.env.length //0 instead of 1 or 10
Now, if we define range
as a lazy val
then the problem goes away and a.env.length
yields 1. I am not able to understand why? (because the moment new Array[Int](range)
is called, I suppose, it will call the getter
for range
from subclass and that will return 0.
Can someone clarify, why lazy val
solves this issue.