Higher-order functions are functions that either take one or more functions as parameters or return a function as a result. In Scala, higher-order functions are a fundamental aspect of functional programming and enable you to write more modular and expressive code. They allow you to abstract over behaviors and operations, making your code more flexible and reusable.
Here are some examples of higher-order functions in Scala:
map:
The map function is a higher-order function that applies a given function to each element of a collection and returns a new collection with the results.
val numbers = List(1, 2, 3)
val doubled = numbers.map(_ * 2) // Result: List(2, 4, 6)
filter:
The filter function takes a predicate function and returns a new collection containing only the elements that satisfy the predicate.
val numbers = List(1, 2, 3, 4, 5)
val evenNumbers = numbers.filter(_ % 2 == 0) // Result: List(2, 4)
reduce:
The reduce function combines elements of a collection using a binary operator.
val numbers = List(1, 2, 3, 4, 5)
val sum = numbers.reduce(_ + _) // Result: 15
foldLeft and foldRight:
The foldLeft and foldRight functions are more general forms of reduce that take an initial value.
val numbers = List(1, 2, 3, 4, 5)
val product = numbers.foldLeft(1)(_ * _) // Result: 120
Function Composition:
Function composition combines two or more functions to create a new function. This can be achieved using the compose and andThen methods.
val addOne: Int => Int = _ + 1
val double: Int => Int = _ * 2
val composed: Int => Int = addOne.compose(double)
val result = composed(3) // Result: 7 (3 * 2 + 1)
Currying:
Currying involves transforming a function that takes multiple arguments into a series of functions, each taking a single argument. This can be achieved using the curried method.
val add: (Int, Int) => Int = _ + _
val curriedAdd: Int => Int => Int = add.curried
val result = curriedAdd(3)(5) // Result: 8