Type classes February 5, 2013
Type classes were originally developed in Haskell as a disciplined alternative to ad-hoc polymorphism. Type classes have been shown to provide a type-safe solution to important challenges in software engineering and programming languages such as, for example, retroactive extension of programs. They are also recognized as a good mechanism for concept-based generic programming ...
As it turns out type classes are a good way to
- extend functionality of our types without having to change original code
- to write generic code based on concepts
Sounds nice, but lets see what we have to do to get it.
First we need to define our "Concept". The concept is a typed trait which defines some functionality we expect to have. We will use a very simple Concept with only one method describe, which gives a text description of our concept.
Next we need to create some "Models" which are implementations of our Concept. The models can be defined as implicit classes so that there is an automatic conversion of the type they implement to the concept model.
The result is that whenever a concept method is used on a type, the compiler will try to automatically convert that type into a concept model. If a model is available the conversion will succeed, the type will be elevated to our concept and the method will do what we expect, otherwise we get a compiler error.
We see here that without changing the implementation of the Int or List[Int] classes of scala we were able to extend their functionality and give them a describe method which to the user of our concept looks exactly like a regular method.
Hence we can write our code generic and based on concepts and use models to convert our usual types to the concepts. As we saw we can different models for different parts of the application, so an html description can be different that a text description, but the "client code" is exactly the same.