维基 Contravariant_method_argument_type说重写方法将子类型化规则作为函数类型,但除了一种支持逆变参数类型之外,没有其他语言。我也想不出使用它有什么好处。
例子:
class AnimalShelter {
Animal getAnimalForAdoption() { ... }
void putAnimal(Animal animal) { ... }
}
class CatShelter extends AnimalShelter {
@Overriding
Cat getAnimalForAdoption() { return new Cat(); }
@Overriding
void putAnimal(Object animal) { … }
}
我的问题是:
- 重写方法的逆变参数类型是否有用?如果是,它在哪里?
- 方法是函数吗?为什么 Scala 对函数类型和覆盖方法类型有不同的规则?
最佳答案
Is contravariant argument type of overriding method any of good use? if yes, where it is?
翻译自 Sather documentation 的示例:
interface Carnivore {
void eat(Meat food);
}
interface Herbivore {
void eat(Plant food);
}
interface Omnivore extends Carnivore, Herbivore {
// overrides both above eat methods,
// since Meat and Plant are subtypes of Food
void eat(Food food);
}
Is method a function?
在 Scala 中?不,但它可以转换为函数。
Why Scala has different rule for function type and overriding method type?
因为覆盖方法类型必须遵循 JVM 的规则。 可以通过创建桥接方法来完成(在上面的例子中,添加方法 eat(Plant)
和 eat(Meat)
只是调用 eat(Food)
),类似于协变返回类型的实现方式,但它会增加语言的复杂性而没有太大好处。
关于java - 逆变方法参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22586976/