The type class design pattern
A lot of times when we write software, we encounter similarities between different implementations. An important principle of good code design is to avoid repetition and it is known as do not repeat yourself (DRY). There are multiple ways that help us to avoid repetitions—inheritance, generics, and so on.
One way to make sure we do not repeat ourselves is through type classes. The purpose of type classes is to:
Note
Define some behavior in terms of operations that a type must support in order to be considered a member of the type class.
A concrete example would be Numeric
. We can say that it is a type class and defines the the operations: addition, subtraction, multiplication, and so on, for the Int
, Double
, and such other classes. We have actually already encountered type classes earlier in this book in Chapter 4, Abstract and Self Types. Type classes are the ones that allow us to implement ad-hoc polymorphism.
Type class example
Let's see an actual example that...