为什么cons的参数类型不对?
trait List[+A] {
def cons(hd: A): List[A]
}
编译器给你错误:
covariant type A occurs in contravariant position in type A of value hd
因为方法参数算作逆变位置,但A是协变的。
让我们假设这个方法声明可以编译。然后我们可以这样做:
class ListImpl[A] extends List[A] {
override def cons(hd: A): List[A] = ???
}
val strings: List[String] = new ListImpl[String]
val values: List[Any] = strings // OK, since List[String] <: List[Any] (in List[A], A is covariant)
values.cons(13) // OK(??), since values's static type is List[Any], so argument of cons should be Any, and 13 conforms to type Any
上面最后一行真的好吗?我们在values 上致电cons。 values 与 strings 相同,strings 是 ListImpl[String] 类型的对象。所以最后一行中的cons 调用期待String 参数,但是我们传递了Int,因为values 的静态类型是List[Any] 和Int 符合Any。这里肯定有问题 - 应该归咎于哪条线?答案是:cons 方法声明。要解决此问题,我们必须从逆变位置(在 cons 声明中)删除协变类型参数 A。或者,我们可以使 A 非协变。
另请参阅以下问题:#1、#2。
...cons 不是遇到问题了吗?
trait List[+A] {
def cons[B >: A](v: B): List[B]
}
val animal_list: List[Animal] = List(tiger, dog) // We are assuming that List.apply and concrete implementation of List is somewhere defined.
不,animal_list.cons(tiger) 调用类型正确。
我假设Animal 是Dog 和Tiger 的常见超类型,而dog 和tiger 分别是Dog 和Tiger 的实例。
在animal_list.cons(tiger) 调用中,A 和B 类型参数都实例化为Animal,因此cons 方法采用以下形式:
def cons[Animal >: Animal](v: Animal): List[Animal]
Animal >: Animal 约束得到满足,因为:
超类型和子类型关系是自反的,这意味着一个类型
既是其自身的超类型,又是其子类型。 [source]
cons 的参数是Tiger,符合Animal 类型,因此方法调用是类型正确的。
请注意,如果您强制将 B 实例化为 Tiger,例如 animal_list.cons[Tiger](tiger),那么此调用将不会是类型正确的,并且您会收到编译器错误。
查看类似示例here。