Scala case class has a default toString function. But when this case class extends a trait with an existing toString() function, it will be rendered useless. How can I prevent this situation?
OK here is the easist answer:
override def toString = ScalaRunTime._toString(this)
end of story:)
Here's a workaround I think may work, it may be too much ceremony, you decide. It involves a trait
.
trait StandardToString { this:Product =>
override def toString = productPrefix + productIterator.mkString("(", ",", ")")
}
Now trying it with some samples:
trait Human {
override def toString() = "Human"
}
case class European(firstName:String) extends Human
and running it with the trait:
scala> new European("Falco") with StandardToString
res0: European with StandardToString = European(Falco)
of course with the trait
you are left with
scala> new European("Adele")
res1: European = Human
It's more precise to say that the case class toString
is not generated, rather than that it is overridden.
This isn't much of an answer or workaround.
scala> trait X { override def toString = "X" }
defined trait X
scala> case class Y(i: Int) extends X
defined class Y
scala> Y(42)
res0: Y = X
scala> case class Y(i: Int)
defined class Y
scala> class Z(x: Int) extends Y(x) with X { override def toString = super[Y].toString }
defined class Z
scala> new Z(42)
res1: Z = Y(42)
You can't do that with a trait:
scala> trait R extends Y { override def toString = super[Y].toString }
<console>:9: error: Implementation restriction: traits may not select fields or methods from super[C] where C is a class
trait R extends Y { override def toString = super[Y].toString }
^
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With