在Scala中具有相同行为的几个案例类

问题描述 投票:0回答:1

我基于以下几点定义一些案例类 Exception 具有相同的行为(源头)

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)
}

所有这些新的异常都是重复相同的代码。我想摆脱多余的代码重复。我试图使用临时的通用基类和特征,但没有成功。请帮我去除多余的重复代码。

scala exception case-class code-duplication
1个回答
3
投票

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)

这是因为案例类是隐式的 Product的,例如,定义

case class Foo(msg: String)

被编译器扩展为类似

case class Foo(msg: String) extends Object with Product with Serializable
© www.soinside.com 2019 - 2024. All rights reserved.