Understanding type classes

A type class represents a group of types that share a common behavior. A type class is to a type what a class is to an object. As with traditional classes, a type class can define methods. These methods can be invoked on all types that belong to the type class.

Type classes were introduced in the Haskell programming language. However, thanks to the power of implicits, we can also use them in Scala. In Scala, type classes are not built-in language constructs (like they are in Haskell) and, as a result, we need to write a bit of boilerplate code to define them.

In Scala, we declare a type class by using trait, which accepts a type parameter. For instance, let's define a Combine type class that allows for combining ...

Get Scala Programming Projects now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.