开发者

In Scala, is it possible to use implicits to automatically override toString?

In Java, I would do something like

class MyDate extends java.util.Date {
  public String toString() { ... }
}

MyDate date = new MyDate

A little bit clunky. In Scala, is it possible to override toString whilst still using regular java.util.Date instead of MyDate. I have an inkling implicits are involved but would be 开发者_开发问答happy to use any technique


Implicit conversions can only work if the type being converted does not already have a method with a given signature. As everything has a toString, it is not possible to override this by pimping.

What you might do is use a typeclass (akin to scalaz.Show) which looks like this:

trait Show[-A] {
  def show(a : A): String
}

Then you can use show everywhere instead of toString. Ideally what you want then is to make the Show[Any] instance a very low priority implicit.

implicit val DateShow = new Show[Date] { def show(d : Date) = "whatever" }

trait LowPriorityShows {
  implicit val AnyShow = new Show[Any] { def show(a : Any) = a.toString }
}

P.S. The reason I would not suggest using scalaz.Show is that the return type is List[Char], which is just not practicable for most uses

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜