协方差和逆变编程语言 [英] Covariance and contravariance in programming languages

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

问题描述

任何人都可以解释我,协方差和逆变的概念
编程语言原理是什么?

Can anyone explain me, the concept of covariance and contravariance in programming languages theory?

推荐答案

协方差的是pretty简单和一些集合类的角度看,最好想列表。我们可以的参数化的的列表类与某些类型参数 T 。也就是说,我们的名单中包含键入 T 一些 T 的元素。清单将是协变,如果

Covariance is pretty simple and best thought of from the perspective of some collection class List. We can parameterize the List class with some type parameter T. That is, our list contains elements of type T for some T. List would be covariant if

S是牛逼当且仅当列表[S]的子类型列表的一个亚型[T]

S is a subtype of T iff List[S] is a subtype of List[T]

(这里我使用的数学定义的当且仅当的意思的当且仅当的。)

(Where I'm using the mathematical definition iff to mean if and only if.)

这是一个列表[苹果] 列表[水果] 。如果有一些程序,它接受一个列表[水果] 作为参数,并且我有一个列表[苹果] ,那么我可以通过这个作为一个有效参数。

That is, a List[Apple] is a List[Fruit]. If there is some routine which accepts a List[Fruit] as a parameter, and I have a List[Apple], then I can pass this in as a valid parameter.

def something(l: List[Fruit]) {
    l.add(new Pear())
}

如果我们的集合类列表是可变的,那么协方差是没有意义的,因为我们可能会认为我们的程序可以添加一些其他的水果(这是不是一个苹果)如上。因此,我们应该只喜欢的一成不变的集合类被协变!

If our collection class List is mutable, then covariance makes no sense because we might assume that our routine could add some other fruit (which was not an apple) as above. Hence we should only like immutable collection classes to be covariant!

这篇关于协方差和逆变编程语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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