Kotlin Higher-Order Functions

A higher-order function is a function that accepts another function as a parameter, returns a function, or both. This makes your code more flexible — you can change the behavior of a function without rewriting it.

Passing a Function as a Parameter

fun operate(a: Int, b: Int, action: (Int, Int) -> Int): Int {
    return action(a, b)
}

fun main() {
    val sum = operate(10, 5) { x, y -> x + y }
    val diff = operate(10, 5) { x, y -> x - y }
    val prod = operate(10, 5) { x, y -> x * y }

    println(sum)   // 15
    println(diff)  // 5
    println(prod)  // 50
}

How It Works


fun operate(a, b, action) {
    return action(a, b)
}
         │
         │  You pass a different "action" each time:
         │
         ├── { x, y -> x + y }  → adds
         ├── { x, y -> x - y }  → subtracts
         └── { x, y -> x * y }  → multiplies

Same function, different behavior depending on the lambda.

Returning a Function

fun getMultiplier(factor: Int): (Int) -> Int {
    return { number -> number * factor }
}

fun main() {
    val triple = getMultiplier(3)
    val tenTimes = getMultiplier(10)

    println(triple(7))      // 21
    println(tenTimes(7))    // 70
}

Built-In Higher-Order Functions

Kotlin's standard library is full of higher-order functions for collections:

map — Transform Each Element

val prices = listOf(100, 250, 80, 400)
val discounted = prices.map { it * 0.9 }
println(discounted)  // [90.0, 225.0, 72.0, 360.0]

filter — Keep Matching Elements

val scores = listOf(45, 82, 61, 30, 93, 55)
val topScores = scores.filter { it >= 60 }
println(topScores)   // [82, 61, 93]

reduce — Combine All Into One

val numbers = listOf(1, 2, 3, 4, 5)
val total = numbers.reduce { acc, item -> acc + item }
println(total)  // 15

fold — Reduce with an Initial Value

val total = numbers.fold(100) { acc, item -> acc + item }
println(total)  // 115 (starts from 100)

any and all — Test Conditions

val ages = listOf(14, 22, 18, 30, 17)

println(ages.any { it >= 18 })   // true (at least one adult)
println(ages.all { it >= 18 })   // false (not all are adults)
println(ages.none { it > 50 })   // true (no one over 50)

Chaining Higher-Order Functions

val students = listOf("Alice", "Bob", "Charlie", "David", "Emma")

val result = students
    .filter { it.length > 3 }         // names longer than 3 chars
    .map { it.uppercase() }           // convert to uppercase
    .sorted()                          // sort alphabetically

println(result)
// [ALICE, CHARLIE, DAVID, EMMA]

Custom Higher-Order Function

fun measureTime(label: String, block: () -> Unit) {
    val start = System.currentTimeMillis()
    block()
    val elapsed = System.currentTimeMillis() - start
    println("$label took ${elapsed}ms")
}

fun main() {
    measureTime("Sorting") {
        val list = (1..10000).shuffled().sorted()
        println("Sorted ${list.size} items")
    }
}

Practical Example: Report Pipeline

data class Sale(val product: String, val amount: Double, val region: String)

fun main() {
    val sales = listOf(
        Sale("Laptop",  45000.0, "North"),
        Sale("Phone",   18000.0, "South"),
        Sale("Tablet",  22000.0, "North"),
        Sale("Watch",   8000.0,  "East"),
        Sale("Earbuds", 3500.0,  "South")
    )

    val northRevenue = sales
        .filter { it.region == "North" }
        .map { it.amount }
        .fold(0.0) { acc, amt -> acc + amt }

    println("North region revenue: ₹$northRevenue")
    // North region revenue: ₹67000.0
}

Leave a Comment

Your email address will not be published. Required fields are marked *