user79074
user79074

Reputation: 5280

Whats the best way to restore the default implementation of a case class toString

Say I do the following:

trait A {
    val i: Int
    override def toString = s"A($i)"
}

case class B(i: Int, j: Int) extends A

println(B(2, 3))

This will give me the output:

A(2)

Is there a way I can make B.toString revert to the default toString for a case class without me having to explicitly write:

override def toString = s"B($i,$j)"

Upvotes: 0

Views: 100

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170815

It used to be

override def toString = scala.runtime.ScalaRunTime._toString(this)

but that object was removed in 2.12 EDIT: it was only removed from ScalaDoc, but still exists.

To avoid relying on ScalaRunTime._toString, you can define it yourself:

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

Upvotes: 2

Mario Galic
Mario Galic

Reputation: 48420

Perhaps

trait A {
  val i: Int
  override def toString = this match {
    case p: Product => scala.runtime.ScalaRunTime._toString(p)
    case _ => s"A($i)"
  }
}

case class B(i: Int, j: Int) extends A

class Foo extends A {
  override val i = 42
}

B(2, 3)
new Foo

which outputs

res0: B = B(2,3)
res1: Foo = A(42)

Upvotes: 2

Related Questions