Type classes in Scala

March 11, 2012

Scala supports ad-hoc polymorphism via traits, context bounds, and implicits.

The type class pattern

Start with a generic trait with a single type parameter:

trait Showable[S] {
  def show(s: S): String

Using a context bound, pull in an implicit instance of the type class:

object Stdout {
  def printLine[S: Showable](s: S): Unit =

Write a concrete, implicit instance of the type class:

implicit object IntShowable extends Showable[Int] {
  def show(s: Int): String =
    s"The number ${s}"

Use it:

Stdout.printLine(42) // prints "The number 42" to stdout

Type classes