How to set superclass field value before its initialization ?

Overriding fields and properties in Scala is straightforward. To do that we can simply use the override keyword. However, it doesn't apply for the case when the superclass needs the overridden values to compute the values of other fields.

The solution for that is the use of early member definition syntax where the overridden values are put inside a block just after the extends keyword like { override val field1... } with ParentClass syntax. You can find a real example in the following use case:

class Parent {
  val id = 10
  val idMultipliedBy2 = id * 2
}
class ChildWithOverride extends {override val id = 20} with Parent {
}
class ChildWithoutOverride extends Parent {
  override val id = 30
}

"child class" should "override the parent field" in {
  val childWithoutOverride = new ChildWithoutOverride
  val childWithOverride = new ChildWithOverride

  childWithOverride.idMultipliedBy2 shouldEqual 40
  // If you add some debugging, you'll see that the overridden id inside the class body is
  // set to 0 and not 30
  childWithoutOverride.idMultipliedBy2 shouldEqual 0
}

Please notice that this syntax applies only to the fields. The methods can still be overridden with the classical def... syntax.