Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding fields in subclasses

Tags:

scala

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?

like image 552
Konstantin Milyutin Avatar asked Jan 16 '23 22:01

Konstantin Milyutin


1 Answers

Prelude:

Scala does not allow you to override vars, 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 vals covariantly, because they can only be read (once they have been initialised).

Examples:

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()
}
like image 87
Malte Schwerhoff Avatar answered Jan 29 '23 16:01

Malte Schwerhoff