从外部访问抽象类型成员

皮特

使用抽象类型成员时,如果不使用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
阿列克谢·罗曼诺夫(Alexey Romanov)

编译器将不会仅在其类型时s查看type-checking的定义y因此,它只知道s.headParam,并且它A是抽象的。要让编译器知道s.head.getInt,它必须知道s.headis IParam

或者,您可以这样看:如果对此类型进行了检查,则可以更改的定义,sval s = Set[Param](SParam("s"))无需更改任何类型。但是很明显,y: Int不应该进行类型检查。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章