Kotlin Higher-Order Functions - Functions as Parameters
Kotlin supports higher-order functions, which are functions that can take other functions as parameters or return functions as results. This powerful feature allows you to write more flexible and reusable code. In this guide, we'll explore how to use higher-order functions in Kotlin.
Basic Higher-Order Function
In Kotlin, you can pass a function as a parameter to another function. Here's a simple example:
fun operateOnNumbers(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
val addition = operateOnNumbers(3, 4) { x, y -> x + y }
val subtraction = operateOnNumbers(10, 5) { x, y -> x - y }
println("Addition: $addition")
println("Subtraction: $subtraction")
In this example, the `operateOnNumbers` function takes two integers and a lambda expression representing an operation. You can pass different operations as parameters.
Lambda as an Argument
Higher-order functions are commonly used for functions like `filter`, `map`, and `reduce`. For instance, filtering a list of numbers:
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evenNumbers = numbers.filter { it % 2 == 0 }
println("Even numbers: $evenNumbers")
The lambda expression inside the `filter` function defines the filtering criteria.
Custom Higher-Order Functions
You can create custom higher-order functions to encapsulate specific behavior. For example, a `repeat` function:
fun repeat(times: Int, action: () -> Unit) {
for (i in 1..times) {
action()
}
}
repeat(3) {
println("Hello, Kotlin!")
}
The `repeat` function takes the number of times and an action to execute repeatedly.
Conclusion
Kotlin's support for higher-order functions is a powerful tool for writing clean, flexible, and expressive code. It allows you to pass functions as parameters and build more generic and reusable components. Understanding and using higher-order functions is essential for becoming proficient in Kotlin.
Happy coding!