Higher-Order Functions & Currying
Explore advanced functional concepts like higher-order functions and currying to create flexible and reusable code.
Unlocking Higher-Order Functions
Welcome to Lesson 2! In functional programming, functions are powerful. They aren't just for calculating values; they can also be treated like any other data.
This means functions can be passed as arguments to other functions, or even returned as results from them. When a function does this, it's called a Higher-Order Function (HOF).
- HOFs take one or more functions as arguments.
- HOFs return a function as a result.
- Or both!
HOF in Action: `map`
One of the most common HOFs in Scala is map. It transforms each element of a collection by applying a given function to it, returning a new collection.
Try running this simple example:
object Main {
def main(args: Array[String]): Unit = {
val numbers = List(1, 2, 3)
val doubledNumbers = numbers.map(x => x * 2)
println(s"Original: $numbers")
println(s"Doubled: $doubledNumbers")
}
}All lessons in this course
- Functions as First-Class Values
- Higher-Order Functions & Currying
- Immutability and Side Effects