更新时间:2022-10-20 15:27:06
在这里,似乎没有成员的单例类型在某种程度上是类型等效的.也许这是一个错误(您提交了一张票).例如,以下会产生运行时错误:
密封 trait Parent案例对象男孩扩展父case 对象 Girl extends Parent特质 HasGirl {val x: Girl.type}case class Thing(x: Boy.type) extends HasGirl {def y: Girl.type = (this: HasGirl).x}val t = 东西(男孩)t.y//ClassCastException !
如果我添加一个成员,你会得到一个编译时错误:
密封 trait Parent案例对象男孩扩展父case 对象 Girl extends Parent { def hello = 1234 }特质 HasGirl {val x: Girl.type}case class Thing(x: Boy.type) extends HasGirl
:57: 错误:覆盖了 Girl.type 类型的特征 HasGirl 中的值 x;值 x 具有不兼容的类型case class Thing(x: Boy.type) extends HasGirl^
Given a simple Algebraic Data Type of 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
I defined a trait:
scala> trait HasGirl {
| val x: Girl.type
| }
defined trait HasGirl
Then, I created a case class that implemented HasGirl
, but provided an x
value of Boy.type
.
scala> case class Thing(x: Boy.type) extends HasGirl
defined class Thing
I had expected a compile-time error, since I don't see how an x
of type Boy.type
conforms to val x: Girl.type
.
What's going on here?
It seems that singleton types without members are type-equivalent somehow here. Perhaps it's a bug (you filed a ticket). For example, the following produces a runtime-error:
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 !
If I add a member, you get a compile-time error:
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 ^