Typeclass in Scala
What we will cover today
A little history
Why typeclass
Relevant features
Alternatives
serialize(123)
serialize("hello world")
serialize(List(1, 2, 3))
serialize(Map('a -> 1, 'b -> 2, 'c -> 3))
A little terminology
trait Serializable[A] {
def serialize(x: A): String
}
object Serializable {
implicit val itemSerializable = new Serializable[Item] {
def serialize(x: Item) = ???
}
}
def serialize[A](x: A)(implicit s: Serializable[A]): String = s.serialize(x)
Our first typeclass
Ords.scala
First use case
Coerces.scala
Second use case
ShowReads.scala
The M word
Monoids.scala
Higher-kinded type
Foldables.scala
Questions.map(Answer(_))
Source code:
https://github.com/weihsiu/typeclasses
Avoid method overloading:
http://stackoverflow.com/questions/2510108/why-avoid-method-overloading
Kind-projector:
https://github.com/non/kind-projector
Simulacrum:
https://github.com/mpilquist/simulacrum
Scalaz:
https://github.com/scalaz/scalaz
Cats: