意外的特质行为

Kev*_*ith 18 scala traits

给出一个简单的代数数据类型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
Run Code Online (Sandbox Code Playgroud)

我定义了一个特征:

scala> trait HasGirl { 
     |   val x: Girl.type
     | }
defined trait HasGirl
Run Code Online (Sandbox Code Playgroud)

然后,我创建了一个实现的case类HasGirl,但提供了一个xBoy.type.

scala> case class Thing(x: Boy.type) extends HasGirl
defined class Thing
Run Code Online (Sandbox Code Playgroud)

我曾预料到编译时错误,因为我没有看到x类型是如何Boy.type符合的val x: Girl.type.

这里发生了什么?

0__*_*0__ 1

似乎没有成员的单例类型在这里以某种方式是类型等效的。也许这是一个错误(您提交了一张票)。例如,以下内容会产生运行时错误:

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 !
Run Code Online (Sandbox Code Playgroud)

如果我添加成员,您会收到编译时错误:

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
Run Code Online (Sandbox Code Playgroud)
<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
                        ^
Run Code Online (Sandbox Code Playgroud)