Scala Higher Order Functions

Reading Time: 2 minutes

Higher order function is a function that either takes a function as argument or returns a function. In other words we can say a function which works with function is called higher order function.

Higher order function allows you to create function composition, lambda function or anonymous function etc.

Let’s see an example.

Passing a Function as Parameter in a Function

object MainObject  extends App {
    functionExample(25, multiplyBy2)                   // Passing a function as parameter

  def functionExample(a:Int, f:Int=>AnyVal):Unit = {
    println(f(a))                                   // Calling that function
  }
  def multiplyBy2(a:Int):Int = {
    a*2
  }
}

Output: 50

Function Composition

In scala, functions can be composed from other functions. It is a process of composing in which a function represents the application of two composed functions.

Let’s see an example.

object MainObject extends App {
    var result = multiplyBy2(add2(10))      // Function composition  
    println(result)
  
  def add2(a:Int):Int = {
    a+2
  }

  def multiplyBy2(a:Int):Int = {
    a*2
  }
}

Output: 24

Anonymous (lambda) Function

Anonymous function is a function that has no name but works as a function. It is good to create an anonymous function when you don’t want to reuse it latter.

You can create anonymous function either by using => (rocket) or _ (underscore) wild card in scala.

Let’s see an example.

object MainObject extends App {
    var result1 = (a:Int, b:Int) => a+b         
    var result2 = (_:Int)+(_:Int)              
    println(result1(10,10))
    println(result2(10,10))
  }

Output:

20
20

Scala Multiline Expression

Expressions those are written in multiple lines are called multiline expression. In scala, be carefull while using multiline expressions.

The following program explains about if we break an expression into multiline, the scala compiler throw a warning message.

Let’s see an example for failed.

def add1(a:Int, b:Int) = {  
        a  
        +b  
    }

The above program does not evaluate complete expression and just return b here. So, be careful while using multiline expressions.

Output:

MainObject.scala:3: warning: a pure expression does nothing in statement 
position; you may be omitting necessary parentheses
        a
        ^
one warning found

10

You can apply following ways to avoid above problem.

Let’s see an example.

object MainObject {  
    def add2(a:Int, b:Int) = {  
        a+b 
         
    }  
    def add3(a:Int, b:Int) = {  
        (a+b)  
    }  
    def main(args: Array[String]) = {  
        var result2 = add2(10,10)  
        var result3 = add3(10,10)  
        println(result2+"\n"+result3)  
    }  

Output:

20

20

Scala Function Currying

In scala, method may have multiple parameter lists. When a method is called with a fewer number of parameter lists, then this will yield a function taking the missing parameter lists as its arguments.

In other words it is a technique of transforming a function that takes multiple arguments into a function that takes a single argument.

Let’s see an example.

object MainObject {  
    def add(a:Int)(b:Int) = {  
        a+b  
    }  
    def main(args: Array[String]) = {  
        var result = add(10)(10)  
        println("10 + 10 = "+result)  
        var addIt = add(10)_  
        var result2 = addIt(3)  
        println("10 + 3 = "+result2)  
    }  
}  

Output:

10 + 10 = 20
10 + 3 = 13

Scala Nested Functions

Scala is a first class function language which means it allows you to passing function, returning function, composing function, nested function etc. An example below explain about how to define and call nested functions.

Let’s see an example.

object MainObject {  
    def add(a:Int, b:Int, c:Int) = {  
        def add2(x:Int,y:Int) = {  
            x+y  
        }  
        add2(a,add2(b,c))  
    }  
    def main(args: Array[String]) = {  
        var result = add(10,10,10)  
        println(result)  
    }  
}  

Output:

30

References

https://docs.scala-lang.org/th/tour/higher-order-functions.html

Stay tune for more blogs!! Keep Learning 🙂

knoldus

Written by 

Meenakshi Goyal is a Software Consultant and started her career in an environment and organization where her skills are challenged each day, resulting in ample learning and growth opportunities. Proficient in Scala, Akka, Akka HTTP , JAVA. Passionate about implementing and launching new projects. Ability to translate business requirements into technical solutions. Her hobbies are traveling and dancing.

Leave a Reply