scala – 类型成员和协方差
发布时间:2020-12-16 19:02:58 所属栏目:安全 来源:网络整理
导读:我猜,“类型方差注释”(和 – )不能应用于“类型成员”.为了自己解释,我考虑了以下 example abstract class Box {type T; val element: T} 现在如果我要创建类StringBox我必须扩展Box: class StringBox extends Box { type T = String; override val elemen
我猜,“类型方差注释”(和 – )不能应用于“类型成员”.为了自己解释,我考虑了以下
example
abstract class Box {type T; val element: T} 现在如果我要创建类StringBox我必须扩展Box: class StringBox extends Box { type T = String; override val element = ""} 所以我可以说Box在T类中是自然的协变量.换句话说,类型成员的类在这些类型中是协变的. 是否有意义 ? 解决方法
Box在T型中是不变的,但这并不意味着没有什么可以看到的.
abstract class Box { type T def get: T } type InvariantBox = Box { type T = AnyRef } type SortofCovariantBox = Box { type T <: AnyRef } 改变方差的情况是类型暴露的程度和方式.抽象类型更不透明.但是你应该在这个副本中玩这些问题,这很有趣. # get a nightly build,and you need -Ydependent-method-types % scala29 -Ydependent-method-types abstract class Box { type T def get: T } type InvariantBox = Box { type T = AnyRef } type SortofCovariantBox = Box { type T <: AnyRef } // what type is inferred for f? why? def f(x1: SortofCovariantBox,x2: InvariantBox) = List(x1,x2) // how about this? def g[U](x1: Box { type T <: U},x2: Box { type T >: U}) = List(x1.get,x2.get) 等等. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |