Kotlin
Beginner
1 min read
Higher-Order Functions and Lambdas
Example
// Higher-order function accepting a function parameter
fun applyTwice(x: Int, operation: (Int) -> Int): Int =
operation(operation(x))
// Returning a function
fun multiplier(factor: Int): (Int) -> Int = { n -> n * factor }
fun main() {
// Lambda stored in a variable
val double: (Int) -> Int = { x -> x * 2 }
println(applyTwice(3, double)) // 12
// Trailing lambda syntax
val result = applyTwice(5) { it + 10 }
println(result) // 25
// Returned function
val triple = multiplier(3)
println(triple(7)) // 21
// Function reference
fun square(n: Int) = n * n
println(applyTwice(4, ::square)) // 256
// Collection operations with lambdas
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val evens = numbers.filter { it % 2 == 0 }
val doubled = numbers.map { it * 2 }
val sumEvens = numbers.filter { it % 2 == 0 }.sumOf { it }
println(evens) // [2, 4, 6, 8, 10]
println(doubled) // [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
println(sumEvens) // 30
// Multi-line lambda with explicit parameter names
val categorised = numbers.groupBy { n ->
if (n % 2 == 0) "even" else "odd"
}
println(categorised)
}