I am referring book "Scala for the Impatient" for learning purpose. I found some example of construction order problem and solution of early definition.
The book has tried to showcase the problem with following class :
class Creature {
val range: Int = 10
val env: Array[Int] = new Array[Int](range)
}
class Ant extends Animal {
override val range: Int = 2
}
Here, as per the construction order problem, while creating an instance of class Ant
, the super class Creature
constructor is called and the env array is initialised with default Int value zero.
To solve the problem, they have mentioned three possible solutions :
- Declare the val as final
- Declare val as lazy in super class
- Use early definition syntax
It is easy to understand the point#2 and point#3 logically.
But how can we solve this problem by declaring the range
field as final
in sub class ?
I tried with following solution and it worked. But I am not able to logically relate here how overriding a field
as final
in subclass can solve this ?
package ed2 {
class Creature {
val range: Int = 10
val env: Array[Int] = new Array[Int](range)
}
class Ant extends Creature {
final override val range = 2
}
}
Note : One important point to note here is, we are able to produce this behaviour while deferring the type declaration of the final overridden field in subclass final override val range = 2
. This code snippet returns zero if we declare field type in subclass.
How the compiler treats final
fields of subclass ? Does it gives first priority to final members for initialisation ?