Kotlin

Higher-Order Functions

admin by @admin ADMIN
3d ago
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
Functions that take or return other functions. Foundation for streams, callbacks, DSLs — and an alternative to interfaces with a single method.
Kotlin
Raw
// Takes a function as a parameter
fun <T> retry(times: Int, action: () -> T): T {
    var lastError: Throwable? = null
    repeat(times) {
        try { return action() }
        catch (e: Throwable) { lastError = e }
    }
    throw lastError!!
}

// Returns a function
fun multiplier(factor: Int): (Int) -> Int = { it * factor }

fun main() {
    val triple = multiplier(3)
    println(triple(7))                                  // 21

    val result = retry(3) {
        if (Math.random() < 0.7) throw Exception("flaky")
        "success"
    }
    println(result)

    // Pass method reference instead of a lambda
    val upper: (String) -> String = String::uppercase
    println(upper("hello"))                             // HELLO
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.