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

scala – “Overriding”继承了方差

发布时间:2020-12-16 10:03:50 所属栏目:安全 来源:网络整理
导读:这感觉非常基本;对不起,我很抱歉. 考虑 trait Foo[+T] { def t : T } trait Bar[+S,+T] extends Foo[T] { def s : S } trait Baz[+S,T] extends Foo[T] { def s : S } Foo中T的协方差是否自动适用于Baz,即使Baz中的T没有标记为协变? Bar和Baz的行为会有任何
这感觉非常基本;对不起,我很抱歉.

考虑

trait Foo[+T] { def t : T }  
trait Bar[+S,+T] extends Foo[T] { def s : S }  
trait Baz[+S,T] extends Foo[T] { def s : S }

Foo中T的协方差是否自动适用于Baz,即使Baz中的T没有标记为协变? Bar和Baz的行为会有任何有意义的区别吗?

(四处游戏,这两种形式似乎很难区分.如果它们相同,那么Baz形式不会发出警告或发出错误信号就会感觉很脏,因为单独看Baz你会期望T不会变形.)

解决方法

不,Baz [T]不会继承Foo [T]的协方差.必须明确标记协方差.这是一个例子,

class Foo[+T] {}
class Baz[T] extends Foo[T] {}

(new Foo[String]) : Foo[Any] // Ok: Foo[+T] is covariant
(new Baz[String]) : Foo[Any] // Ok: Baz[String] <: Foo[String] <: Foo[Any]
(new Baz[String]) : Baz[Any] // Error: Baz[T] is invariant in type T

(编辑:李大同)

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

    推荐文章
      热点阅读