Sunday, 25 December 2011

Type classes in scala

I've recently come across the concept of type classes. They seemed to be widely used in functional languages.

The basic idea of type classes is that they offer code reuse by identifying common properties of seemingly different objects.

Lets look at operation sum. The same operation could be applied to numbers or to strings or even lists. In case of numbers sum will mean arithmetic sum of numbers, in case of strings and lists it would mean concatenation.

The basic logic is the same, if we express it in terms of an add operation i.e.:
sum(1, 2, 3) == (1 add 2) add 3
sum( list1, list2, list3) == (list1 add list2) add list3

Let's have look at the code example:


The sum function uses reduce function to "add" elements. In order to use the right add function for the type of elements in the list, we are using scala implicits. When compiler finds an expression sum(List("abc", "def", "ghi")) it looks for an implicit of type AddTypeClass[String], and uses it in order to compute the sum of elements.

I realise this case is overly simplistic, but I hope you get the idea!

For more examples of type classes check out Typeclassopedia.

No comments:

Post a Comment