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 :

1 2 3 | (i:Int) => {i*2} |

The function literal can be assigned to a variable :

1 2 3 | val doubler = (i:Int) => {i*2} |

Now the variable doubler is an instance of the function and can used in following way :

1 2 3 | 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 :

1 2 3 4 5 | 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.

1 2 3 | val sum = (x:Int, y:Int)=> x+y |

Now we can pass the sum function to operation as :

1 2 3 | 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 :

1 2 3 | 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 :

1 2 3 | (num:Int) => num * 2; |

Next, we define a method that returns the anonymous method as follows :

1 2 3 | def doubler()= (num:Int) => num * 2; |

We can assign doubler() to a variable as :

1 2 3 | 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:

1 2 3 4 5 6 7 8 9 10 11 12 13 | 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, www.topjavatutorial.com. All rights reserved. On republishing this post, you must provide link to original post