Type class example

Let's see an actual example that is also somehow useful to developers in this case. In machine learning, developers tend to use some statistical functions quite often in their work. There are statistical libraries and, if we try them out, we will see that these functions exist for different numeric types—Int, Double, and so on. Now, we could come up with something simple and implement these functions for all the numeric types we think about. This, however, is not feasible and makes our library impossible to extend. Moreover, statistical functions have the same definitions, no matter the type, so we don't want to repeat our code as many times as there are numeric types.

So let's first define our type class:

trait Number[ ...

Get Scala Design Patterns - Second Edition 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.