Typeclasses, (or type classes), are most famously a language feature of Haskell that has gained interest in the Scala community. Here I describe the basic pattern with references for further study.
What is a type class and why do I need it?
Type classes are useful to solve several fundamental challenges in software engineering and programming languages. In particular type classes support retroactive extension: the ability to extend existing software modules with new functionality without needing to touch or re-compile the original source. [1]
The Scala library includes a few typeclasses such as scala.math.Numeric and scala.math.Ordering, and Scalaz is all typeclasses.
Scala enables the typeclass pattern using traits and implicits, and whilst Scala's implementation is more verbose than Haskell's, it comes with greater flexibility. Haskell only allows a single typeclass instance globally, whereas Scala allows any number to be available.
Furthermore, Scala allows default implementations to be made available if no others can be found.
For a deeper understanding see the references at the bottom of the blog.
Show me the code!
(You can copy and paste this into your favourite IDE)
Now to use the type class.
Summary
So we defined a typeclass which has been extended with new instances. If the transformer typeclass were part of a library, we can retroactively extend the library with new behaviour supporting new types not originally conceived of in the library. Furthermore, the library supplied types and the new ones work together perfectly.
We encourage discussion of our blog posts on our Gitter channel.
Please review our Community Guidelines before posting there.
We encourage discussion in good faith, but do not allow combative, exclusionary, or harassing behaviour.
If you have any questions, contact us!