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?

有帮助吗?

解决方案

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.

其他提示

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
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top