In Scala we can override fields. I'm wondering what are the advantages of this? Normally we just inherit the field and set its value in constructor of subclass. Could someone give examples?
Scala does not allow you to override var
s, since they would have to be overridden covariantly (field read) as well as contravariantly (field write), which means that they must actually be invariant. Scala does allow you to override val
s covariantly, because they can only be read (once they have been initialised).
Here are two use cases, both illustrate a specialisation. Assume the following minimal class hierarchy:
class A
class B extends A
Example 1:
In the following example we use field overriding to specialise the subclass. That is, when working with a Super
instance, all we know is that super.f
contains an object of type A
. However, when working with a Sub
instance, we know that sub.f
contains a specialised object of type B
.
class Super {
val f: A = new A()
}
class Sub extends Super {
override val f: B = new B()
}
Example 2:
A different use case for field overriding is overriding a method with a field. This possibility allows us to specify an interface in a general way, that is, we leave potential implementors the choice of computing the value of f
on every call, but also, to compute f
only once (during instantiation). In the latter case f
is constant, which allows the compiler to perform more aggressive optimisations.
trait Interface {
def f: A = new A()
}
class Impl extends Interface {
override val f: A = new A()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With