在 Scala 中具有相同行为的几种情况 类

Several case classes with the same behavior in Scala

我根据 Exception 定义了一些情况 classes 具有相同的行为 ()

case class Foo(msg: String) extends Exception {
    override def toString: String = scala.runtime.ScalaRunTime._toString(this)
}
case class Bar(msg: String) extends Exception {
    override def toString: String = scala.runtime.ScalaRunTime._toString(this)
}
case class Boo(msg: String) extends Exception {
    override def toString: String = scala.runtime.ScalaRunTime._toString(this)
}

所有这些新异常都重复相同的代码。我想摆脱冗余代码重复。我没有成功尝试使用临时公共基础 class 和特征。请帮我删除多余的代码重复。

ScalaRunTime._toString 接受一个 Product 参数

def _toString(x: Product): String =
  x.productIterator.mkString(x.productPrefix + "(", ",", ")")

因此尝试定义

trait ProductException extends Exception with Product {
  override def toString: String = scala.runtime.ScalaRunTime._toString(this)
}

然后

case class Foo(msg: String) extends ProductException
Foo("Live long and prosper")
// res1: Foo = Foo(Live long and prosper)

这是可行的,因为 case 类 是隐含的 Product,例如,defnining

case class Foo(msg: String)

被编译器扩展为

case class Foo(msg: String) extends Object with Product with Serializable