Type Classes and Implicits

Scala uses implicits to implement type classes — a pattern for ad-hoc polymorphism.

Type Class Example

trait Show[A] {
  def show(value: A): String
}

Implementing the Type Class

implicit object IntShow extends Show[Int] {
  def show(value: Int): String = s"Int: $value"
}

Using Context Bounds

def printValue[A: Show](value: A)(implicit ev: Show[A]): Unit = {
  println(ev.show(value))
}
← PrevNext →