Kotlin

inline Functions — Zero-Cost Lambdas

admin by @admin ADMIN
Jun 12, 2026
Jun 1, 2026
Public
0 0 up · 0 down Sign in to vote
`inline fun` copies the body (including lambda bodies) into the call site at compile time. Result: no `Function` object allocated for the lambda; `return` from inside the lambda exits the enclosing function.
Kotlin
Raw
// Without `inline` — every call allocates a Function object for the lambda
fun runIfTrue(condition: Boolean, action: () -> Unit) {
    if (condition) action()
}

// With `inline` — the lambda body is inlined at the call site
inline fun runIfTrueFast(condition: Boolean, action: () -> Unit) {
    if (condition) action()
}

// Non-local return: only legal in inline lambdas
fun findUser(users: List<String>): String? {
    users.forEach { name ->          // forEach is inline in stdlib
        if (name.startsWith("a")) return name    // returns from findUser!
    }
    return null
}

// `crossinline` if you can\'t allow non-local return
inline fun delayed(crossinline action: () -> Unit) {
    Thread { action() }.start()      // can't `return` out of action here
}

fun main() {
    runIfTrueFast(true) { println("hello") }
    println(findUser(listOf("bob", "alice", "carol")))   // alice
}
Tags

Save your own code snippets

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