Higher Order Functions in Scala

Higher Order functions take other functions as parameters and return function as result, i.e., passing functions as parameters to other functions and to get a new function as result. The best example of Higher Order functions in Scala is map().

This concept will be clear if we look at some example code snippets explaining it.

 

object HigherOrder{
  def operation(x: Int, y: Int, func: (Int, Int) => Int): Int = func(x,y)

  def main(args: Array[String]){
    var output = operation(10,20, (x,y)=>x+y)
    println(output) //Prints sum of 10,20 i.e., 30

    output = operation(10,20, (x,y)=>x*y)
    println(output) //Prints multiplication of 10,20 i.e., 200 
  }
}

 

In the above example we have defined a function with name operation, which takes two Int variable and a function that takes two integers and returns an integer.

After that we have defined main function in which we have called the function operation by passing 10 and 20 as first two parameters and an anonymous function which returns the sum of the two elements passed to it. Printing this gives us the output 30.

We have again called the same function with the 10 and 20 as first two parameters but the function passed is multiplication. Which gives us the output 200.

 

Please comment you thoughts about this post..

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *