Override toString of type scala

I have a type in Scala:

type Fingerprint = Seq[(Int, Int)] 

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

+7
tostring scala
source share
2 answers

There is good reason to use a type approach for this kind of task instead of Scala toString (which may just be annoying due to bugs with Java), and the fact that you can't bolt a toString on an arbitrary type is one of them. For example, you can write the following using the Scalaz Show 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 is also good reason to prefer a class-based type approach to one based on implicit classes or other implicit instances of a conversion type class, and it is usually much easier to reason and debug.

+8
source share

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 limit the zoom limit:

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

All Articles