意外的特质行为 [英] Unexpected Trait Behavior

查看:50
本文介绍了意外的特质行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个简单的 Parent 代数数据类型:

scala>密封性状父母定义的特征父标度>案例对象男孩扩展父定义对象男孩标度>case 对象 Girl 扩展 Parent定义对象女孩

我定义了一个特征:

scala>特质 HasGirl {|val x: Girl.type|}定义特征 HasGirl

然后,我创建了一个实现 HasGirl 的案例类,但提供了 Boy.typex 值.

scala>case class Thing(x: Boy.type) extends HasGirl定义类事物

我预计会出现编译时错误,因为我看不到 Boy.type 类型的 x 如何符合 val x: Girl.输入.

这是怎么回事?

解决方案

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

 密封 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
                        ^

这篇关于意外的特质行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆