What are higher-order functions in Scala?
Instruction: Define higher-order functions and provide examples of their usage in Scala.
Updated
A higher-order function accepts a function, returns a function, or both. This lets callers supply behavior separately from the code that applies it.
def applyTwice(value: Int)(f: Int => Int): Int = f(f(value))
def incrementBy(amount: Int): Int => Int = value => value + amount
@main def higherOrderExample(): Unit = {
val numbers = List(1, 2, 3, 4)
assert(numbers.map(_ + 1) == List(2, 3, 4, 5))
assert(numbers.filter(_ % 2 == 0) == List(2, 4))
assert(applyTwice(3)(_ * 2) == 12)
val addFive = incrementBy(5)
assert(addFive(7) == 12)
}
map and filter receive functions; incrementBy returns one that captures its amount. applyTwice makes its repetition explicit. Higher-order functions
Common uses include transformations, predicates, configurable algorithms and callbacks. A function value can still mutate shared state, perform I/O or throw, so higher-order syntax does not guarantee purity, immutability or speed. Consider evaluation count and order when passing effects, and use a plain named method when abstraction would make a small operation harder to follow.