In Scala functions are first-class values which means functions are just like other values in Scala. We can pass functions as arguments to other functions, stored the function in values, return the functions as a result from other functions.
So, function which takes other function as parameters or return as result are called higher-order
functions. Any Scala function with following properties can be higher-order functions. Higher-order functions let us write more general code and reusable code and lead us to DRY
principle ( Don’t Repeat Yourself ).
Let’s us look the below example:
Above two functions are the instance of $\sum_{a}^{b} f(n)$ for the different function $f$. So the above functions can be factored as follow:
In above sum function we have parameter f which is function with type Int => Int
which means it takes Int
and also return Int
. Since the argument of sum is function, sum is higher-order function. Now the above function can be refactored using sum function:
Simply the anonymous functions means function without name. These functions are defined as a literals and are syntactic sugar for more tedious long definition. The above square and id function can be defined with anonymous as:
The part before =>
is function parameter and after that is function body. So the above two function can be written with anonymous function which helps to avoid polluting top-level namespace.
Currying allows us to apply some argument to the function now and other at later time when required. The above sum function can be curried in the following way:
The above sum function returns the sumF function which takes the number bound as arguments and returns and do the calculation. The above function can be utilized in the following way:
The above function is applied in the following ways:
where function sum is applied to identity and square function and and the resulting function is applied to the bound $1\ to\ 10$.
The function application associates to the left. So for the arguments list args1 and args2:
Moreover, any functions with multiple arguments can be curried. For example:
To curry the above function, we can use scala curried
Higher-order, anonymous and curried functions provides way to abstract the code in higher level and more reusable code. Composing and reusing the code provides benefits through out the program and provides more flexibility in code.