Extensibility with Higher-Order Functions

Functions that can take other functions as parameters are called higher-order functions. They reduce code duplication, increase reuse, and make code concise as well. We can create functions within functions, assign them to references, and pass them around to other functions. Scala internally deals with these so-called function values by creating them as instances of special classes. In Scala, function values are really objects.

Let’s rewrite the previous example using function values. With this new version, we can perform different operations, such as summing numbers or counting the number of even numbers on a range of values.

We’ll start by first extracting the common code into a method named totalResultOverRange ...

Get Pragmatic Scala 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.