A Simple Introduction to Higher Order Functions in Scala

Reading Time: 4 minutes

Overview

In this blog, we’ll understand the concept of higher order function in Scala. Also, we’ll learn about some of the most commonly used higher order functions in Scala.

Higher Order Function

A function is said to be a Higher Order Function if it can take another function as an argument or returns a function as its result. This is possible because of the fact that functions are first-class citizens in Scala.

How to define a Higher Order Function

1. Function that takes another function as an argument
object FunctionThatTakesFunction extends App {

  def math(a:Int, b:Int, fun:(Int,Int)=>Int):Int = fun(a,b)

  val sum = math(5, 6, (a,b) => a+b)
  val diff = math(10, 4, (a,b) => a-b)

  println(s"sum is $sum")
  println(s"diff is $diff")

}

Output:

sum is 11
diff is 6

In the above example, we’ve defined a math function with three parameters.The third parameter is actually a function fun that takes two arguments of type Int and the return type of this function is also Int. So here the math function is actually a higher order function as it is expecting a function as its third argument. That’s why when we call the math function, we are passing a anonymous function(that takes two arguments) as a third argument for the math function.

2. Function that returns a function as its result
object FunctionThatReturnsFunction extends App {

  def math(name: String): (Int, Int) => Int = (x: Int, y: Int) => {
    name match {
      case "add" => x + y
      case "product" => x * y
      case "divide" => x/y
      case "subtract" => x - y
    }
  }

  def add: (Int, Int) => Int = math("add")
  def sub: (Int, Int) => Int = math("subtract")
  def product: (Int, Int) => Int = math("product")
  def div: (Int, Int) => Int = math("divide")
  
  println(s"Addition of two numbers: ${add(5,8)}")
  println(s"Subtraction of two numbers: ${sub(15,8)}")
  println(s"Product of two numbers: ${product(5,8)}")
  println(s"Division of two numbers: ${div(16,8)}")
}

Output:

Addition of two numbers: 13
Subtraction of two numbers: 7
Product of two numbers: 40
Division of two numbers: 2

In this example, we’ve defined a math function which takes the name of the operation as a parameter and its return type is (Int, Int) => Int. This means that a function is returned that takes two Integers and returns a Integer.

Commonly Used Higher Order Functions In Scala

Let’s see some of the most commonly used higher order functions in Scala:

1. map

map is a function that transforms one collection into another collection by applying a function to each element. It’s our job to describe how to transform each element.

It has the following signature:

Example:

Note: The collection type remains but the element type may change.

2. flatMap

flatMap is identical to the map function, but the only difference is that in flatMap the inner grouping of an item is removed and a sequence is generated. It can be defined as a blend of map method and flatten method.

It has the following signature:

Example:

3. filter

filter function takes a predicate and selects the elements from the data structure which satisfy the given predicate. A predicate is a unary function that returns a boolean value.

The filter function looks like:

Example:

4. reduce

reduce is a bit different function compare to the previous ones. It takes all the elements in a collection and combines them using a binary operation to produce a single value.

Example:

In this example, we’ve a sequence of earnings, and we want to calculate the sum of them. To do that, we need to provide a more complex function. That function consists of two elements: an accumulator acc and a current element x.

An accumulator is responsible for keeping the state of calculations performed on our collection.

By default, reduce calls reduceLeft, which traverses the collection from left to right. If we want reversed order, we can use reduceRight.

Conclusion

In this blog, we’ve learned about higher-order functions in Scala. They are quite powerful and empower us to write simple, boilerplate-free, and readable code.

For more such blogs, visit Knoldus Blogs

References

Scala Documetation

Baeldung Scala

Written by 

Prateek Gupta is a Software Consultant at Knoldus Inc. He likes to explore new technologies and believes in writing clean code. He has a good understanding of programming languages like Java and Scala. He also has good time management skills. In his leisure time, he like to do singing and watch SciFi movies.

1 thought on “A Simple Introduction to Higher Order Functions in Scala5 min read

Comments are closed.

%d bloggers like this: