matanox
matanox

Reputation: 13686

type classes in Scala - a minimal self-contained example

I looked at examples for type class scenarios and how to imitate this Haskell-ish concept in scala, e.g. at http://danielwestheide.com/blog/2013/02/06/the-neophytes-guide-to-scala-part-12-type-classes.html. I think they are all too much involved and narrative-laden than they could be. Can you provide an authoritative minimal example for polymorphism using type classes rather than inheritance and mixins?

Thanks!

Upvotes: 1

Views: 134

Answers (1)

0__
0__

Reputation: 67280

// type class
trait Show[A] { def show(x: A): String }

// usage
def greet[A](x: A)(implicit sh: Show[A]) = s"Hello ${sh.show(x)}"

// example instance
implicit object ShowDouble extends Show[Double] {
  def show(x: Double) = f"$x%1.3f" // format with three digits
}

greet(math.Pi)  // "Hello 3.142"

Upvotes: 6

Related Questions