简体   繁体   中英

Several case classes with the same behavior in Scala

I define some case classes based on Exception with identical behavior ( source )

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

All these new exceptions repeat same code. I want to rid of redundant code duplication. I unsuccessfully tried to use interim common base class and traits. Please, help me remove excess code duplication.

ScalaRunTime._toString takes a Product argument

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

hence try defining

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

and then

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

This works because case classes are implicitly Product s, for example, defnining

case class Foo(msg: String)

is expanded by compiler to something like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM