协变方法参数类型 [英] Contravariant method argument type

查看:63
本文介绍了协变方法参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

wiki Contravariant_method_argument_type 说,替代方法将子类型化规则作为函数类型,但是除一种语言之外,没有一种语言支持相反的参数类型。我也想不出使用它的好处。

wiki Contravariant_method_argument_type says overriding method has the subtyping rule as function type, but no language except one support contravariant argument type. I also not able to come up with any idea of benefit to use that.

示例:

class AnimalShelter {
    Animal getAnimalForAdoption() {      ...        }         
    void putAnimal(Animal animal) {      ...        }   
}

class CatShelter extends AnimalShelter {
    @Overriding        
    Cat getAnimalForAdoption() {  return new Cat();    }        
    @Overriding                    
    void putAnimal(Object animal) {      …        }     
}

我的问题是:


  1. 覆盖方法的自变量类型是否有用?如果是,在哪里?

  2. 方法是函数吗?为什么Scala对于函数类型和覆盖方法类型具有不同的规则?


推荐答案


压倒性参数类型的重写方法有用吗?如果是,它在哪里?

Is contravariant argument type of overriding method any of good use? if yes, where it is?

Sather文档

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中?否,但是可以将其转换为函数。

In Scala? No, but it can be converted to a function.


为什么Scala对于函数类型和覆盖方法类型有不同的规则?

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

因为重写方法类型必须遵循JVM的规则。 可以通过创建桥接方法来完成(在上述情况下,添加方法 eat(Plant) eat(Meat )仅调用 eat(Food)),类似于实现协变返回类型的方式,但是这样会增加语言的复杂性利益。

Because overriding method types has to follow JVM's rules. It could be done by creating bridge methods (in the case above, adding methods eat(Plant) and eat(Meat) which just call eat(Food)), similarly to the way covariant return type is implemented, but it would add complexity to the language without much benefit.

这篇关于协变方法参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆