使用抽象类型成员时,如果不使用asInstanceOf,则无法从外部使用该类型,还有其他选择吗?为什么抽象类型不让自己被“覆盖”,所以它知道它是Int还是String?
scala> trait Param { type A
| val x:A
| def get:A = x
| }
scala> case class IParam(override val x:Int) extends Param {type A = Int}
defined class IParam
scala> case class SParam(override val x:String) extends Param {type A = String}
defined class SParam
scala> val s = Set[Param](IParam(1), SParam("s"))
s: scala.collection.immutable.Set[Param] = Set(IParam(1), SParam(s))
scala> val y:Int = s.head.get
<console>:26: error: type mismatch;
found : Param#A
required: Int
val y:Int = s.head.get
编译器将不会仅在其类型时s
查看type-checking的定义y
。因此,它只知道s.head
是Param
,并且它A
是抽象的。要让编译器知道s.head.get
是Int
,它必须知道s.head
is IParam
。
或者,您可以这样看:如果对此类型进行了检查,则可以更改的定义,s
而val s = Set[Param](SParam("s"))
无需更改任何类型。但是很明显,y: Int
不应该进行类型检查。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句