这不是类型擦除。你得到这个结果是因为DItem 得到了从Mitem 继承的toString() 实现。你必须重写它才能得到你想要的
class DItem(override val id: String, override val name: String, val name2: String) extends MItem(id, name) {
override def toString = s"DItem($id, $name, $name2)"
}
所以这是一个结果:
scala> val d = new DItem("1", "one", "another one")
d: DItem = DItem(1, one, another one)
scala> println(d)
DItem(1, one, another one)
从案例类继承几乎总是一个坏主意,因为除了toString 后继类will also inherit equals and hashCode。
另一个缺点是此类后继类的模式匹配有限,即不可能在 case 分支中使用此类类,并且可能导致混淆错误。
示例
case class A(id: String)
class B(id: String, name: String) extends A(id)
new B("foo", "bar") match {
case A(id) => println(id)
case other => println(other)
}
你可能认为这段代码没有错误,但你会得到
<console>:17: error: constructor cannot be instantiated to expected type;
found : A
required: B
case A(id) => println(id)
^
但是,如果您明确推断 B 实例的类型,它将起作用
scala> new B("foo", "bar").asInstanceOf[A] match {
| case A(id) => println(id)
| case other => println(other)
| }
foo
所以...从案例类继承非常容易出错且令人困惑,除非您知道自己在做什么,否则应避免使用。