SyntaxStudy
Sign Up
Kotlin Higher-Order Functions and Lambdas
Kotlin Beginner 1 min read

Higher-Order Functions and Lambdas

Kotlin treats functions as first-class citizens: you can store them in variables, pass them as arguments, and return them from other functions. A higher-order function is simply one that takes a function parameter or returns a function. Lambda expressions are written with curly braces. When a lambda is the last argument to a function, Kotlin allows you to move it outside the parentheses — this trailing-lambda syntax is the foundation of Kotlin's DSL capabilities. When a lambda has exactly one parameter, you can omit the parameter declaration and refer to it as it. Function references (::functionName) let you pass an existing named function wherever a lambda is expected, avoiding unnecessary wrapper 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)
}