编程语言
首页 > 编程语言> > java – 逆变方法参数类型

java – 逆变方法参数类型

作者:互联网

wiki Contravariant_method_argument_type说overriding方法将子类型规则作为函数类型,但除了一个支持逆变量参数类型之外没有其他语言.我也无法想出使用它的任何好处.

例:

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?

在斯卡拉?不,但它可以转换为函数.

Why Scala has different rule for function type and overriding method type?

因为重写方法类型必须遵循JVM的规则.它可以通过创建桥接方法来完成(在上面的例子中,添加方法eat(Plant)和eat(Meat)只调用eat(Food)),类似于协变返回类型的实现方式,但它会增加复杂性没有太多好处的语言.

标签:java,scala,covariance,contravariance,subtyping
来源: https://codeday.me/bug/20190717/1491252.html