给定一个简单的代数数据类型Parent
:
scala> sealed trait Parent
defined trait Parent
scala> case object Boy extends Parent
defined object Boy
scala> case object Girl extends Parent
defined object Girl
我定义了一个特质:
scala> trait HasGirl {
| val x: Girl.type
| }
defined trait HasGirl
然后,我创建了一个案例类来实现HasGirl
,但提供了一个x
的价值Boy.type
.
scala> case class Thing(x: Boy.type) extends HasGirl
defined class Thing
我原以为会出现编译时错误,因为我不知道如何x
类型的Boy.type
符合val x: Girl.type
.
这里发生了什么?
似乎没有成员的单例类型在这里以某种方式是类型等效的。也许这是一个错误(您提交了一张票)。例如,以下内容会产生运行时错误:
sealed trait Parent
case object Boy extends Parent
case object Girl extends Parent
trait HasGirl {
val x: Girl.type
}
case class Thing(x: Boy.type) extends HasGirl {
def y: Girl.type = (this: HasGirl).x
}
val t = Thing(Boy)
t.y // ClassCastException !
如果我添加成员,您会收到编译时错误:
sealed trait Parent
case object Boy extends Parent
case object Girl extends Parent { def hello = 1234 }
trait HasGirl {
val x: Girl.type
}
case class Thing(x: Boy.type) extends HasGirl
<console>:57: error: overriding value x in trait HasGirl of type Girl.type;
value x has incompatible type
case class Thing(x: Boy.type) extends HasGirl
^
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)