Scala - 为什么无法重写超类方法

3
  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

我的问题是为什么G不起作用,考虑到以下条件:(A=>Unit)是(B=>Unit)的子类型。
implicitly[(A => Unit) <:< (B => Unit)]
1个回答

5
原因很简单:JVM不允许基于参数类型的逆变重载,它只允许基于返回类型的协变重载。
请点击这里了解有关Scala上述影响的讨论。
来自维基百科

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.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接