Home:ALL Converter>How to avoid scala's case class default toString function being overridden?

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

Ask Time:2014-12-14T11:10:02         Author:tribbloid

Json Formatter

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?

Author:tribbloid,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/27465951/how-to-avoid-scalas-case-class-default-tostring-function-being-overridden
tribbloid :

OK here is the easist answer:\n\noverride def toString = ScalaRunTime._toString(this)\n\n\nend of story:)",
2014-12-14T07:53:22
Daniel Hinojosa :

Here's a workaround I think may work, it may be too much ceremony, you decide. It involves a trait.\n\ntrait StandardToString { this:Product =>\n override def toString = productPrefix + productIterator.mkString(\"(\", \",\", \")\")\n}\n\n\nNow trying it with some samples:\n\ntrait Human {\n override def toString() = \"Human\"\n}\n\ncase class European(firstName:String) extends Human\n\n\nand running it with the trait:\n\nscala> new European(\"Falco\") with StandardToString\nres0: European with StandardToString = European(Falco)\n\n\nof course with the trait you are left with\n\nscala> new European(\"Adele\")\nres1: European = Human\n",
2014-12-14T05:18:51
yy