Google News
logo
Scala - Interview Questions
What is a higher-order function in Scala? Provide an example.
In Scala, a higher-order function is a function that takes one or more functions as arguments and/or returns a function as its result. In other words, it treats functions as first-class citizens, allowing them to be manipulated and passed around like any other data type.

Here's an example of a higher-order function in Scala :
def operateOnNumbers(a: Int, b: Int, operation: (Int, Int) => Int): Int = {
  operation(a, b)
}

val add: (Int, Int) => Int = (a, b) => a + b
val subtract: (Int, Int) => Int = (a, b) => a - b

val result1 = operateOnNumbers(5, 3, add) // Passes the 'add' function as an argument
val result2 = operateOnNumbers(7, 2, subtract) // Passes the 'subtract' function as an argument

println(result1)
println(result2) ​

Output :

8 //result1
5 //result2​
In this example, `operateOnNumbers` is a higher-order function that takes two integer values `a` and `b`, along with an operation function as arguments. The operation function is defined as `(Int, Int) => Int`, meaning it takes two integers and returns an integer.

The `operateOnNumbers` function applies the operation function to the provided arguments `a` and `b` and returns the result. The `add` and `subtract` functions are defined as separate functions that match the required `(Int, Int) => Int` function signature.

By passing different operation functions (`add` and `subtract`) to the `operateOnNumbers` higher-order function, we can perform different operations on the input numbers.

Higher-order functions enable powerful functional programming techniques, such as function composition, partial function application, and the creation of domain-specific languages (DSLs). They provide flexibility and abstraction, allowing developers to write reusable and modular code.
Advertisement