Higher-order functions in Scala

Category : Scala | Sub Category : Scala Interview Questions | By Prasad Bonam Last updated: 2023-09-27 10:13:20 Viewed : 272


In Scala, higher-order functions are functions that can take other functions as arguments and/or return functions as results. This is a fundamental concept in functional programming and provides a powerful mechanism for abstracting and composing behavior. Higher-order functions enable you to write more modular, reusable, and expressive code.

There are two common types of higher-order functions in Scala:

  1. Functions that Take Functions as Arguments (Function Arguments):

    In Scala, you can define functions that take other functions as arguments. These functions are often used for operations like mapping, filtering, and reducing over collections. One of the most common examples is the map function on collections, which takes a function and applies it to each element in the collection to produce a new collection.

    scala
    val numbers = List(1, 2, 3, 4, 5) // Higher-order function: map val squaredNumbers = numbers.map(x => x * x)

    Here, map is a higher-order function that takes a function (x => x * x) and applies it to each element in the list.

  2. Functions that Return Functions (Function Composition):

    Scala also allows you to define functions that return other functions as results. This is useful for creating new functions by composing existing ones. A common example is function composition, where you combine two functions to create a new one.

    scala
    def add(a: Int): Int => Int = { (b: Int) => a + b } val addTwo = add(2) val result = addTwo(3) // result is 5

    In this example, the add function takes an integer a and returns a function that takes another integer b and adds a to it. This allows you to create specific addition functions like addTwo by partially applying add.

Higher-order functions in Scala are powerful tools for writing more modular and expressive code. They enable you to pass behavior as data, which is a key concept in functional programming, and they are commonly used in libraries, frameworks, and applications to work with collections, implement callbacks, and define custom control structures.

Search
Related Articles

Leave a Comment: