编程语言中的协方差和逆方差有什么区别? [英] What is the difference between covariance and contra-variance in programming languages?

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

问题描述

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

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列表的子类型[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.)

也就是说,列表[Apple] 列表[水果] .如果有一些例程接受 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())
}

如果我们的集合类 List 是可变的,则协方差是没有意义的,因为我们可以假定例程可以像上面那样添加其他水果(不是苹果).因此,我们应该只希望 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天全站免登陆