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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access