简体   繁体   English

Scala较低的类型边界和协方差

[英]Scala lower type bounds and covariance

Im reading this page http://www.scala-lang.org/node/137 , I understand what covariance is and lower bounds as well, but what it's not clear is this line: 我正在阅读这个页面http://www.scala-lang.org/node/137 ,我也明白协方差是什么和下限,但不清楚的是这一行:

Unfortunately, this program does not compile, because a covariance annotation is only possible if the type variable is used only in covariant positions. 不幸的是,这个程序不能编译,因为只有在变量位置使用类型变量时才能进行协方差注释。 Since type variable T appears as a parameter type of method prepend, this rule is broken. 由于类型变量T作为方法前置的参数类型出现,因此该规则被破坏。

why elem has to be an instance of a supertype of T , if ListNode is already covariant why elem cannot be prepended to the current list. 为什么elem必须是超类型T的实例,如果ListNode已经是协变的,为什么elem不能被添加到当前列表中。

class Super             {override def toString = "Super"}
class Sub extends Super {override def toString = "Sub"; def subMethod {} }
val sup = new Super
val sub = new Sub

Imagine the following were allowed: 想象一下,允许以下内容:

// invalid code
class Foo[+T] {
  def bar(x: T) = println(x)
}

Since Foo is covariant on T , this is valid (a simple upcast, since a Foo[Sub] is a Foo[Super] ): 因为FooT上是协变的,所以这是有效的(简单的上传,因为Foo[Sub]Foo[Super] ):

val foo : Foo[Super] = new Foo[Sub] {
  override def bar(x: Sub) = x.subMethod
}

Now foo is, as far as we know, a Foo[Super] like any other, but its bar method won't work, because the bar implementation requires a Sub : 现在foo就像我们所知, Foo[Super]就像其他任何一样,但它的bar方法不起作用,因为bar实现需要一个Sub

foo.bar(sup) // would cause error!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM