子类中的协方差

时间:2014-09-19 16:45:06

标签: scala

sealed trait Option[+A]
case object None extends Option[Nothing]
case class Some[A](get: A) extends Option[A]

class C1() {}
class C2() extends C1 {}
val x1: Some[C1] = Some(new C2)           //> x1  : T.Some[T.C1] = Some(T$C2@4b5695c8)
val x2: Some[C2] = Some(new C2)           //> x2  : T.Some[T.C2] = Some(T$C2@664bb5d8)
// val x3: Some[C1] = x2 // Type mismatch

+ASome[+A]的目的是什么?如果我将其定义为Some[A],它也将是协变的,我理解它继承了Option[A]的协方差。

1 个答案:

答案 0 :(得分:3)

不,不,请考虑这种情况:

sealed trait Maybe[+A]
case object Empty extends Maybe[Nothing]
case class Just[A](x: A) extends Maybe[A]

scala> val j: Maybe[AnyRef] = Just[String]("Hello")
j: Maybe[AnyRef] = Just(Hello)

和此:

scala> val j: Just[AnyRef] = Just[String]("Hello")
<console>:10: error: type mismatch;
 found   : Just[String]
 required: Just[AnyRef]
Note: String <: AnyRef, but class Just is invariant in type A.
You may wish to define A as +A instead. (SLS 4.5)
       val j: Just[AnyRef] = Just[String]("Hello")

我理解将某种类型的变量声明为Some是愚蠢的,但我已经看过这样的代码。