标签:java scala covariance contravariance subtyping
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。