Search code examples
scalaexceptioncase-classcode-duplication

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.


Solution

  • 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 Products, 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