【发布时间】:2013-03-27 00:08:24
【问题描述】:
假设在 Scala repl 中做了以下声明:
class Animal
class Bird extends Animal
class Chicken extends Bird
type SubType = t forSome { type t <: Bird }
type SuperType = t forSome { type t >: Bird }
正如我所料,SubType 属于符合Bird 的类型。由于Animal 是Bird 的超类,SubType 类型的变量不能保存Animal 类型的值:
scala> val foo: SubType = new Animal
<console>:10: error: type mismatch;
found : Animal
required: SubType
val foo: SubType = new Animal
然而这个推论并不像我预期的那样:
scala> val foo: SuperType = new Chicken
foo: SuperType = Chicken@1fea8dbd
分配成功,这些也成功了:
scala> val foo: SuperType = 2
foo: SuperType = 2
scala> val foo: SuperType = "wtf?"
foo: SuperType = wtf?
scala>
再次,这里是SuperType:
type SuperType = t forSome { type t >: Bird }
根据SLS 4.3,
类型声明 type t [tps ] >: L <: u> 声明t 是一个具有下限类型 L 和上限类型 U 的抽象类型。
所以我声明t 是一个具有下限Bird 的抽象类型。 Chicken 不是 Bird 的超类,String 和 Int 也不是。
我想这可能是因为Chicken 是Any,而SuperType 可以存储Any。但是如果我把SuperType的声明改成这样:
type SuperType = t forSome { type t >: Bird <: Animal}
设置Animal 的上限似乎没有任何改变。
问题
首先
我如何将 Chicken Int 和 String 类型的值分配给存在性子句 { type t >: Bird } 和 { type t >: Bird <: Animal} 允许的 SuperType 变量?
第二
引用规范中“A 类型声明 type t [tps ] >: L <: u> 声明 t 是一个抽象类型......”如果没有“抽象”这个词,意义会有什么不同?
【问题讨论】:
标签: scala types covariance existential-type type-bounds