加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 18:32:46 所属栏目:安全 来源:网络整理
导读:我正在阅读本页 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 pos
我正在阅读本页 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.

为什么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

想象一下,允许以下内容:

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

因为Foo在T上是协变的,所以这是有效的(简单的上传,因为Foo [Sub]是Foo [Super]):

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

现在foo就像我们所知,Foo [Super]就像其他任何一样,但它的bar方法不起作用,因为条形实现需要一个Sub:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读