Created
December 25, 2011 18:49
-
-
Save piotrga/1519603 to your computer and use it in GitHub Desktop.
Type classes in scala 2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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