Skip to content

Instantly share code, notes, and snippets.

@piotrga
Created December 25, 2011 18:49
Show Gist options
  • Save piotrga/1519603 to your computer and use it in GitHub Desktop.
Save piotrga/1519603 to your computer and use it in GitHub Desktop.
Type classes in scala 2
def sum[T](list: Seq[T])(implicit typeClass : AddTypeClass[T]) = {
list.reduce(typeClass.add(_,_))
}
trait AddTypeClass[T]{
def add(a:T, b:T) : T
}
implicit val ints = new AddTypeClass[Int]{
def add(a: Int, b: Int) = a+b
}
implicit val strings = new AddTypeClass[String]{
def add(a: String, b: String) = a+b
}
implicit def lists[T] = new AddTypeClass[List[T]]{
def add(a: List[T], b: List[T]) = a:::b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment