O'Reilly logo

Scala Design Patterns - Second Edition by Ivan Nikolov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required