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

╄→尐↘猪︶ㄣ 提交于 2019-12-03 11:22:27
tribbloid

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 }
                                                   ^
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!