Higher-Order Functions in Kotlin
A higher-order function is a function that takes one or more functions as parameters or returns a function.
Basic Example
Kotlin
fun operate(a: Int, b: Int, operation: (Int, Int) -> Int): Int {
return operation(a, b)
}
fun main() {
val sum = { x: Int, y: Int -> x + y }
val product = { x: Int, y: Int -> x * y }
val result1 = operate(2, 3, sum)
val result2 = operate(4, 5, product)
println("Sum: $result1")
println("Product: $result2")
}
Explanation:
operate
function:- Takes three parameters: two integers (
a
andb
) and a functionoperation
. - The
operation
function takes two integers and returns an integer. - It applies the
operation
function toa
andb
and returns the result.
- Takes three parameters: two integers (
- Lambda expressions:
- The
sum
andproduct
lambdas define simple operations: addition and multiplication, respectively.
- The
- Function invocation:
- The
operate
function is called with thesum
andproduct
lambdas as the third argument. - The appropriate operation is performed based on the lambda passed.
- The
More Complex Example: Filtering a List
Kotlin
fun filter(list: List<Int>, predicate: (Int) -> Boolean): List<Int> {
val filteredList = mutableListOf<Int>()
for (element in list) {
if (predicate(element)) {
filteredList.add(element)
}
}
return filteredList
}
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
val evenNumbers = filter(numbers) { it % 2 == 0 }
val oddNumbers = filter(numbers) { it % 2 != 0 }
println("Even numbers: $evenNumbers")
println("Odd numbers: $oddNumbers")
}
Explanation:
filter
function:- Takes a list of integers and a predicate function.
- The predicate function takes an integer and returns a boolean indicating whether to include the element in the filtered list.
- The function iterates over the list, applies the predicate to each element, and adds the matching elements to the filtered list.
- Lambda expressions:
- The lambda expressions
it % 2 == 0
andit % 2 != 0
define the predicates for even and odd numbers, respectively.
- The lambda expressions
Key Points:
- Higher-order functions promote functional programming style.
- Lambda expressions provide concise ways to define functions inline.
- Higher-order functions can be used to create reusable and flexible code.
- Kotlin's standard library provides many built-in higher-order functions like
map
,filter
,reduce
, etc.
By understanding and utilizing higher-order functions, you can write more expressive and elegant Kotlin code.
Komentar
Posting Komentar