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 ...

Get Scala Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.