Scala Higher Order Function
Using methods as function values
The Scala compiler will automatically convert methods into function values for the purpose of passing them into higher-order functions.
In the example above, MyObject.mapMethod is not a function call, but instead is passed to map as a value. Indeed, map requires a function value passed to it, as can be seen in it's signature. The signature for the map of a List[A] (a list of objects of type A) is:
The f: (A) => B part indicates that the parameter to this method call is some function that takes an object of type A and returns an object of type B. A and B are arbitrarily defined. Returning to the first example, we can see that mapMethod takes an Int (which corresponds to A) and returns a String (which corresponds to B). Thus mapMethod is a valid function value to pass to map. We could rewrite the same code like this:
This inlines the function value, which may add clarity for simple functions.
High Order Functions(Function as Parameter)
A higher-order function, as opposed to a first-order function, can have one of three forms:
• One or more of its parameters is a function, and it returns some value.
• It returns a function, but none of its parameters is a function.
•Both of the above: One or more of its parameters is a function, and it returns a function.
Here the map function takes a getFullName(n._1,n._2) function as a parameter. This is called HOF (Higher order function).
Arguments lazy evaluation
Scala supports lazy evaluation for function arguments using notation: def func(arg: => String). Such function argument might take regular String object or a higher order function with String return type. In second case, function argument would be evaluated on value access.
Please see the example: