Reputation: 526
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 subtype of (B=>Unit)
implicitly[(A => Unit) <:< (B => Unit)]
Upvotes: 3
Views: 82
Reputation: 11963
The reason is simple: the JVM doesn't allow overrides based on contravariance over parameter types. It only allows overrides based on covariance of return type.
Take a look here for some discussion about the implications of that on Scala.
From Wikipedia:
Similarly, it is type safe to allow an overriding method to accept a more general argument than the method in the base class:
Ex:
class AnimalShelter { void putAnimal(Animal animal) { ... } } class CatShelter extends AnimalShelter { void putAnimal(Object animal) { ... } }
Not many object oriented languages actually allow this — C++ and Java [and also Scala] would interpret this as an unrelated method with an overloaded name.
Upvotes: 5