Consider this simple Scala class:
class A(val d: Int)
Is there a difference in Scala (either in behaviour or generated bytecode) between
class B(d: Int) extends A(d)
and
class B(override val d: Int) extends A(d)
or are both equivalent? If they are different, what would be the specific usecase for each of them?
Would it be different if A was defined as class A(var d: Int)?
For vals, there is no semantic difference. However, there may be a difference in the generated bytecode. In particular, if a method defined in the derived class refers to
d, it refers to the constructor parameterdrather than to thevalof the same name. This is implemented via an additional private field generated for the derived class.For vars, there is a difference in behavior. Without an override, any methods that refer to
dfrom within the derived class will be referring to the constructor parameter, while callers referencingdfrom outside the class will get the field. In this case, the two values may differ (if the value has changed since construction).Here’s a session that demonstrates the behavior with a var:
This question is related: Idiomatic Scala way to deal with base vs derived class field names?.