Why would someone need a concept such as a type-class? To answer this, we'll first have to understand what a type-class exactly is. As they say, "Type-classes allow us to generalize over a set of types in order to define and execute a standard set of features for those types." Let's try to understand this.
I believe you're aware of the notion of encoding and decoding. Let's think of encoding as applying a certain rule to convert A into a specific pattern. Now, after you encode something, it's in that specific pattern. Decoding is the exact opposite of what we just did: it's changing your type A from the pattern we just created to its original shape. For example, comma-separated values (CSV) can be considered an encoded pattern. Hence, there's a scheme that converts words from a source to CSV format:
trait CSVEncoder[T] { def encode(t: T): List[String] }
We've written a trait named CSVEncoder[T]
. It's time to rephrase what we said for type-classes. CSVEncoder
allows us to generalize...