Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid scala's case class default toString function being overridden?

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?

like image 294
tribbloid Avatar asked Dec 14 '14 03:12

tribbloid


3 Answers

OK here is the easist answer:

override def toString = ScalaRunTime._toString(this)

end of story:)

like image 159
tribbloid Avatar answered Oct 31 '22 23:10

tribbloid


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
like image 44
Daniel Hinojosa Avatar answered Nov 01 '22 00:11

Daniel Hinojosa


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 }
                                                   ^
like image 26
som-snytt Avatar answered Nov 01 '22 00:11

som-snytt