Scala - why can't override superclass method

  class A
  class B extends A

  class D { def get: A = ??? }
  class E extends D { override def get: B = ??? } // OK

  class F { def set(b: B): Unit = ??? }
  class G extends F { override def set(a: A): Unit = ??? } // Compile Error, override nothing

      

my question is why G doesn't work, given that: (A => Unit) is a subtype of (B => Unit)

implicitly[(A => Unit) <:< (B => Unit)]

      

+3


source to share


1 answer


The reason is simple: the JVM does not allow overrides based on contravariance on parameter types. It only allows overrides based on the covariance of the return type.

Look here for a discussion about the implications of this in Scala.



From Wikipedia :

Likewise, it is type safe, allowing the overridden method to take a more general argument than the method in the base class:

Example:

class AnimalShelter {
    void putAnimal(Animal animal) {
        ...
    }
}

class CatShelter extends AnimalShelter {
    void putAnimal(Object animal) {
        ...
    }
}

      

There really aren't many OO languages ​​- C ++ and Java [as well as Scala] interpret this as an overloaded unbound method .

+5


source







All Articles