Kotlin Higher Order Function

Higher-Order Functions in Kotlin

A higher-order function is a function that takes one or more functions as parameters or returns a function. This powerful concept allows for functional programming paradigms and can make your code more concise, expressive, and reusable.

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:

  1. operate function:
    • Takes three parameters: two integers (a and b) and a function operation.
    • The operation function takes two integers and returns an integer.
    • It applies the operation function to a and b and returns the result.
  2. Lambda expressions:
    • The sum and product lambdas define simple operations: addition and multiplication, respectively.
  3. Function invocation:
    • The operate function is called with the sum and product lambdas as the third argument.
    • The appropriate operation is performed based on the lambda passed.

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:

  1. 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.
  2. Lambda expressions:
    • The lambda expressions it % 2 == 0 and it % 2 != 0 define the predicates for even and odd numbers, respectively.

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