【发布时间】:2014-05-14 10:50:35
【问题描述】:
我一直在学习 scala 对协变和逆变参数化类型的使用;下面的示例代码让我有些困惑:
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 下限的逆变,所以
val flat = new Home[Human]
导致编译器错误,这是我所期望的。我的困境是,我创造了一个新的“房子”,但我可以在里面放一个“人”!虽然这也是有道理的,因为“人类”是“事物”,但我天真地期待它会失败!抛开机制不谈,协变、逆变有什么用?
【问题讨论】:
-
您的示例与逆变无关,请参阅Programming in Scala 19.3 以获得深入的解释。
标签: scala covariance contravariance