gpt4 book ai didi

Scala - 为什么无法覆盖父类(super class)的方法

转载 作者:行者123 更新时间:2023-12-03 15:31:30 25 4
gpt4 key购买 nike

  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)]

最佳答案

原因很简单:JVM 不允许基于参数类型逆变的覆盖。它只允许基于返回类型的协方差进行覆盖。

看看here用于讨论它对 Scala 的影响。

来自 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.

关于Scala - 为什么无法覆盖父类(super class)的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26485892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com