In functional programming, functions can be assigned to variables, passed to other functions as parameters, and returned as values from other
functions. Such functions are known as First Class Functions.
A higher-order function is a function which takes a function as argument or returns a function.
Assign function as Variable
We can define a function literal that takes an integer and returns its double in following manner :
(i:Int) => {i*2}
The function literal can be assigned to a variable :
val doubler = (i:Int) => {i*2}
Now the variable doubler is an instance of the function and can used in following way :
doubler(5)
Pass function as Parameter
We can create a function or a method that takes a function as a parameter.
For this, the first step is to create a method that takes a function as a parameter :
def operation(functionparam:(Int, Int) => Int){ println(functionparam(10,5)) }
The operation method takes one parameter named functionparam, which is a function. The functionparam function takes two Int and returns an Int. The operation method returns a Unit that indicates that operation method returns nothing.
Next, lets create a function that matches the signature of functionparam.
val sum = (x:Int, y:Int)=> x+y
Now we can pass the sum function to operation as :
operation(sum);
Any function that matches the signature of functionparam can be passed to operation.
For example, we can create another function diff as follows :
val diff = (x:Int, y:Int)=> x-y
Similar to sum, it can be passed to operation method as operation(diff).
Return a Function
To return a function from another funtion or method, we first need to create an anonymous function.
As an example, lets create an anonymous function that doubles a number :
(num:Int) => num * 2;
Next, we define a method that returns the anonymous method as follows :
def doubler()= (num:Int) => num * 2;
We can assign doubler() to a variable as :
val doubleValue = doubler();
Now, doubleValue(return of doubler()) is equivalent to the anonymous function that doubles a number.
So, we can get the double of 10 as doubleValue(10).
Here is the complete code:
object HelloWorldScala { def main(args: Array[String]) { val doubleValue = doubler(); print("Double of 2 = " + doubleValue(2)); } def doubler() = (num: Int) => num * 2; }
Output
Double of 2 = 4
© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post