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.