本文介绍了Scala的协方差,协方差有什么用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习scala使用协方差和自变量参数化类型化的方法;以下示例代码让我有些困惑:

I've been learning about scala's use of covariance and contravariance parameterized typing; I'm a bit perplexed by the following example code:

class Thing
class Creature extends Thing
class Human extends Creature
class Dog extends Creature

class Home[T >: Creature] {
  private var inside = Set[T]()

  def enter(entering: T) = inside += entering

  def whoIsInside = inside
}

val house = new Home[Thing]
val cage = new Home[Creature]
house enter new Human
cage enter new Dog

据我所知,参数化类Home使用的协方差具有Creature的下限,所以

As I understand it, the parameterized class Home uses contravariance with a lower bound of Creature, so

val flat = new Home[Human]

导致编译器错误,这是我所期望的.我的困境是,我创建了一个新的房子",但我可以在其中放置人类"!虽然这也很有意义,因为人类"是事物",我天真地期望它会失败!抛开机制,协方差,协方差有什么用?

causes a compiler error, which is what I expected. My predicament is, I've created a new 'house' but I can put a 'Human' in it! While this also makes sense because a 'Human' is a 'Thing' I was naively expecting it to fail! Putting aside the mechanics, how is covariance, contravariance useful?

推荐答案

在您的示例中,您可以将T的子类型放入T的集合中,因为U< ;: T也是T.

In your example, you can put subtypes of T into the collection of T, because U <: T is also a T. That is not covariance or contravariance.

协方差就是您的房屋[U]是房屋[T]的子类型,且U

Covariance would be when your House[U] is a subtype of a House[T] for U <: T. So if for example you asked for a House[Creature] you could offer a House[Human] if T was covariant. We use the + on a type parameter for covariance.

例如,

class Home[+T]
val cage: Home[Creature] = new Home[Human]

最有用的示例是对列表使用Nil时,因为Nil是List [Nothing]并且List是协变的.因此,List [Nothing]完全可以替代任何类型的List.

The most useful example of this is when you use Nil for a List, because Nil is a List[Nothing] and List is covariant. So a List[Nothing] can substitute for any type of List at all.

相反性是相反的.如果U

Contravariance is the opposite. That a House[U] is a supertype of House[T] if U <: T. We use the - on a type parameter for contravariance.

例如,

class Home[-T]
val cage: Home[Human] = new Home[Creature]

这篇关于Scala的协方差,协方差有什么用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-30 13:25