What are Higher Order Functions in Scala with Examples

Scala, a powerful programming language, offers a myriad of features that make it a top choice for developers. One such feature is the higher order function. In this guide, we will delve deep into the world of higher order functions in Scala, exploring their definition, usage, and some common examples.

graph TD A[Higher Order Functions] --> B[Accepts Functions] A --> C[Returns Functions] B --> D[map] B --> E[flatMap] B --> F[filter] B --> G[reduce]

What are Higher Order Functions?

Higher order functions are a fundamental concept in functional programming. In Scala, a function is termed as a higher order function if:

  • It accepts another function as an argument.
  • It returns a function as its result.

This capability stems from the fact that Scala treats functions as first-class citizens.

Defining a Higher Order Function in Scala

1. Functions Accepting Other Functions as Arguments

Consider the following example:

Scala
object FunctionTakingFunction extends App {
  def operation(a: Int, b: Int, func: (Int, Int) => Int): Int = func(a, b)

  val addition = operation(5, 6, (x, y) => x + y)
  val subtraction = operation(10, 4, (x, y) => x - y)

  println(s"Addition result: $addition")
  println(s"Subtraction result: $subtraction")
}

In the above code, the operation function is a higher order function. It expects a function func as its third parameter. This function takes two integers and returns an integer.

2. Functions Returning Other Functions

Here's an example:

Scala
object FunctionReturningFunction extends App {
  def arithmetic(operation: String): (Int, Int) => Int = {
    operation match {
      case "add" => (x, y) => x + y
      case "multiply" => (x, y) => x * y
      case "divide" => (x, y) => x / y
      case "subtract" => (x, y) => x - y
    }
  }

  val additionFunc = arithmetic("add")
  val multiplicationFunc = arithmetic("multiply")

  println(s"5 + 3 = ${additionFunc(5, 3)}")
  println(s"5 x 3 = ${multiplicationFunc(5, 3)}")
}

In the above scenario, the arithmetic function returns another function based on the operation string provided.

Popular Higher Order Functions in Scala

Scala offers a plethora of built-in higher order functions. Let's explore some of them:

1. map

The map function transforms a collection by applying a function to each of its elements. The type of the collection remains unchanged, but the element type can vary.

Scala
val numbers = List(1, 2, 3, 4)
val squaredNumbers = numbers.map(x => x * x)
println(squaredNumbers)  // List(1, 4, 9, 16)

2. flatMap

flatMap is similar to map, but it flattens the result, producing a single sequence.

Scala
val strings = List("Hello", "World")
val characters = strings.flatMap(str => str.toList)
println(characters)  // List(H, e, l, l, o, W, o, r, l, d)

3. filter

The filter function selects elements from a collection based on a predicate.

Scala
val numbers = List(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter(x => x % 2 == 0)
println(evenNumbers)  // List(2, 4)

4. reduce

The reduce function combines all elements of a collection using a binary operation.

Scala
val numbers = List(1, 2, 3, 4)
val sum = numbers.reduce((acc, x) => acc + x)
println(sum)  // 10

Conclusion

Higher order functions in Scala provide a robust mechanism to write concise and expressive code. They are a testament to Scala's capabilities in functional programming, enabling developers to write cleaner and more maintainable code.

FAQs:

  • What is a higher order function in Scala?
    • A higher order function in Scala can either accept another function as an argument or return a function as its result.
  • How is map different from flatMap in Scala?
    • The map function transforms a collection by applying a function to each of its elements. In contrast, flatMap does the same but also flattens the result, producing a single sequence.
  • What does the filter function do in Scala?
    • The filter function selects elements from a collection based on a given predicate.
  • How can I combine all elements of a collection in Scala?
    • You can use the reduce function to combine all elements of a collection using a binary operation.

Author