编程语言中协方差和反方差的区别 [英] Difference between Covariance and Contra-variance in programming languages

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

问题描述

有人能解释
编程语言理论中的协方差和逆方差的概念吗?

Can anyone explain the concept of covariance and contravariance in programming language theory?

推荐答案

协方差是非常简单的,最好从某些集合类 List 的角度考虑。我们可以使用某些类型参数 T 参数化 List 类。也就是说,对于某些 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是Tiff的子类型,则List将是协变的。List [S]是List [T]的子类型

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

(当我使用数学定义 iff 表示 if并且仅当时。)

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

也就是说,列表[苹果] 列表[水果] 。如果有一些例程接受 List [Fruit] 作为参数,并且我有一个 List [Apple] ,那么我可以将其作为有效参数传递。

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())
}

如果我们的收藏夹类列表是可变的,因此协方差毫无意义,因为我们可能会假设我们的例程可以像上面那样添加其他水果(不是苹果)。因此,我们应该只希望 immutable 集合类是协变的!

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天全站免登陆