Daniel Cukier
Daniel Cukier

Reputation: 11942

Override toString of a scala type

I have a type in Scala:

  type Fingerprint = Seq[(Int, Int)]

I would like to override the toString of this type. How can I do this?

Upvotes: 7

Views: 1474

Answers (2)

flavian
flavian

Reputation: 28511

Overriding toString may not be the best option here, but there is a simple alternative:

implicit class SeqAug[T <: (_, _)](val seq: Seq[T]) {
   def showInfo: String = {
      seq.map(p => p._1 + " " + p._2).mkString("\n") // or whatever you want.
   }
}
val x = Seq(("test" -> 5))
Console.println(x.showInfo)

You can even restrict the bound of the augmentation:

type Fingerprint = Seq[(Int, Int)]
implicit class SeqAug(val fingerprint: Fingerprint) {
  // same thing
}

Upvotes: 5

Travis Brown
Travis Brown

Reputation: 139028

There are good reasons to use a type class-based approach to this kind of problem instead of Scala's toString (which is arguably just an unpleasant hand-me-down from Java), and the fact that you can't bolt a toString on an arbitrary type is one of them. For example, you could write the following using Scalaz's Show type class:

import scalaz._, syntax.show._

implicit val fingerprintShow: Show[Fingerprint] = Show.shows(
  _.map(p => p._1 + " " + p._2).mkString("\n")
)

And then:

scala> Seq((1, 2), (3, 4), (5, 6)).shows
res0: String = 
1 2
3 4
5 6

There are also good reasons to prefer a type class-based approach to one based on implicit classes or other implicit conversions—type class instances are generally much easier to reason about and debug.

Upvotes: 8

Related Questions