Higher-order functions are functions that either accept other functions as parameters or return a function. In Kotlin, these are a key aspect of functional programming, enabling powerful and flexible code reuse.
1. Defining Higher-Order Functions
A higher-order function takes another function as a parameter. The syntax for passing a function looks like this:
kotlinCopy codefun <T> myFunction(list: List<T>, operation: (T) -> Unit) {
for (item in list) {
operation(item) // Calling the function passed as a parameter
}
}
Here, operation
is a function parameter, which takes a single argument of type T
and returns Unit
(void).
2. Passing a Function
You can pass a lambda or an existing function to a higher-order function:
kotlinCopy codefun printItem(item: String) {
println(item)
}
val items = listOf("Apple", "Banana", "Cherry")
myFunction(items, ::printItem) // Passing a reference to a function
You can also pass a lambda:
kotlinCopy codemyFunction(items) { item ->
println("Item: $item")
}
3. Returning a Function
A higher-order function can also return another function:
kotlinCopy codefun operation(type: String): (Int, Int) -> Int {
return when (type) {
"add" -> { a, b -> a + b }
"multiply" -> { a, b -> a * b }
else -> { a, b -> 0 }
}
}
val addOperation = operation("add")
println(addOperation(2, 3)) // Output: 5
In this example, operation()
returns a function that performs addition or multiplication based on the type passed.
4. Why Use Higher-Order Functions?
- Code Reusability: You can pass different functions to the same higher-order function to modify its behavior without rewriting the entire function.
- Simplified Logic: By using higher-order functions, you reduce boilerplate code, making it easier to read and maintain.
Conclusion
Higher-order functions in Kotlin allow you to write more flexible, reusable, and modular code by passing functions as parameters or returning them. This pattern is particularly useful in functional programming and enables you to create expressive APIs.
Leave a Reply