Scala - Higher-Order Functions



Higher-order functions are functions that can take other functions as parameters. These may return functions as results. So, you can create flexible and reusable code.

Higher-Order Functions

Higher-order functions are functions that operate on other functions. These higher order functions take other functions as arguments or return other functions. So, there can be higher levels of abstraction. Hence more concise and expressive code.

Definition

Higher-order function is a function that does at least one of the following -

  • Takes one or more functions as arguments.
  • Returns a function as its result.

Syntax

The syntax of higher order function in Scala is -

def higherOrderFunction(f: (ParameterType) => ReturnType, x: ParameterType): ReturnType = {
  // function body
}

Example of Higher Order Functions

The following example shows defining and using a higher-order function that takes another function as an argument -

object Demo {
  def applyFunction(f: Int => Int, x: Int): Int = {
    f(x)
  }

  def increment(n: Int): Int = {
    n + 1
  }

  def main(args: Array[String]): Unit = {
    println(applyFunction(increment, 5)) 
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

6

In the example, the applyFunction function is a higher-order function. It takes another function f and integer x as arguments. It applies f to x and returns the result. The increment function is defined to add 1 to a given number. The Demo object calls applyFunction with increment and an integer.

Higher-Order Functions with Multiple Functions

There can be multiple functions as parameters in a Higher-order function. So you can perform more complex operations and compositions.

Syntax

The syntax of multiple functions in a higher order function -

def functionName(param1: Type1, param2: Type2 => ReturnType, param3: Type3 => ReturnType, ...): ReturnType = {
  // function body
}

Example

The following example shows using multiple functions as parameters in a higher-order function.

object Demo {
  def applyFunctions(f1: Int => Int, f2: Int => String, v: Int): String = {
    f2(f1(v))
  }

  def main(args: Array[String]): Unit = {
    val result = applyFunctions(x => x * 2, x => s"Result: $x", 5)
    println(result)  // Result: 10
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

Result: 10

In the example, the applyFunctions method takes two functions: f1 and f2, and an integer v. The function f1 is applied to v first, and then f2 is applied to the result of f1.

Returning Functions from Functions

A function can return another function as its result. So this function is known as higher order function. You can create functions dynamically based on input parameters and return them as a function.

Syntax

The syntax for returning function from a function in Scala -

def higherOrderFunction(x: ParameterType): (AnotherParameterType) => ReturnType = {
  // return a function
  (y: AnotherParameterType) => {
    // function body
  }
}

Example

The following example shows defining and using a higher-order function that returns another function in Scala programming -

object Demo {
  def createMultiplier(factor: Int): Int => Int = {
    (x: Int) => x * factor
  }

  def main(args: Array[String]): Unit = {
    val multiplyBy2 = createMultiplier(2)
    println(multiplyBy2(5)) 
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

10

In the example, the createMultiplier method returns a function that multiplies its input by a given factor. The returned function is then used to multiply the value 5 by 2.

Common Higher-Order Functions in Scala

There are some common higher order functions in Scala.

1. map

The map function is a higher-order function. It applies given function to each element of collection. It returns a new collection with the results.

Syntax

The syntax of the map higher order function -

collection.map(f: (ElementType) => ReturnType): CollectionType

Example

Consider the example of map higher order function in Scala programming -

object Demo {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4, 5)
    val doubled = numbers.map(x => x * 2)
    println(doubled) // List(2, 4, 6, 8, 10)
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

List(2, 4, 6, 8, 10)

2. filter

The filter function is a higher-order function. It selects elements of collection that satisfy a given predicate function.

Syntax

The syntax of the filter higher order function -

collection.filter(p: (ElementType) => Boolean): CollectionType

Example

Consider the example of filter higher order function in Scala programming -

object Demo {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4, 5)
    val evenNumbers = numbers.filter(x => x % 2 == 0)
    println(evenNumbers) // List(2, 4)
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

List(2, 4)

3. reduce

The reduce function is a higher-order function. It combines elements of collection using a given binary function.

Syntax

The syntax of the filter higher order function -

collection.reduce(f: (ElementType, ElementType) => ElementType): ElementType

Example

Consider the example of reduce higher order function in Scala programming -

object Demo {
  def main(args: Array[String]): Unit = {
    val numbers = List(1, 2, 3, 4, 5)
    val sum = numbers.reduce((a, b) => a + b)
    println(sum) // 15
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

15

Higher-Order Functions with Anonymous Functions

You can use higher-order functions with anonymous functions (lambdas) for more concise and flexible code.

Syntax

The syntax of the higher order function with anonymous function -

higherOrderFunction((parameters) => { functionBody }, otherArguments)

Example

The following example shows using a higher-order function with an anonymous function in Scala programming -

object Demo {
  def applyFunction(f: Int => Int, x: Int): Int = {
    f(x)
  }

  def main(args: Array[String]): Unit = {
    println(applyFunction((n: Int) => n * 2, 5)) // 10
  }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

> scalac Demo.scala
> scala Demo

Output

10

In the example, the applyFunction function is used with an anonymous function (n: Int) => n * 2 to double the input value. The Demo object calls applyFunction with anonymous function and integer.

Higher Order Functions Summary

  • Higher-order functions in Scala are functions that either take other functions as parameters or these return a function as results.
  • Higher-order functions provide a way to create more flexible and reusable code.
  • You can also use higher-order functions with collections to perform operations like mapping, filtering, and reducing.
  • You can use higher-order functions with anonymous functions for more concise and expressive code.
Advertisements