Skip to content

Instantly share code, notes, and snippets.

@miguel-vila
Created October 12, 2013 19:08
Show Gist options
  • Save miguel-vila/6953685 to your computer and use it in GitHub Desktop.
Save miguel-vila/6953685 to your computer and use it in GitHub Desktop.
Scala's Typeclass pattern
trait MeasureTypeClass[A]{
def measure(a: A) : Int
}
object TypeClassExample{
def genericMeasure[A : MeasureTypeClass](value: A): Int = {
val measurer = implicitly[MeasureTypeClass[A]]
measurer.measure(value)
}
implicit val stringTypeClass = new MeasureTypeClass[String]{
def measure(string: String): Int = string.length
}
genericMeasure("four")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment