0
0
KotlinHow-ToBeginner · 3 min read

How to Return from Lambda in Kotlin: Simple Guide

In Kotlin, to return from a lambda, use an implicit return by placing the expression as the last line or use a labeled return with return@label to exit the lambda explicitly without returning from the enclosing function.
📐

Syntax

In Kotlin, lambdas can return values implicitly by having the last expression as the return value. To return explicitly from a lambda without exiting the outer function, use a labeled return with return@label.

  • Implicit return: The last expression in the lambda is returned automatically.
  • Labeled return: Use return@label to return from the lambda itself.
kotlin
val numbers = listOf(1, 2, 3, 4, 5)
numbers.forEach label@{
    if (it == 3) return@label  // returns from lambda, continues forEach
    println(it)
}
Output
1 2 4 5
💻

Example

This example shows how to return from a lambda inside a forEach loop. Using return@forEach skips the current iteration without exiting the whole function.

kotlin
fun main() {
    val numbers = listOf(1, 2, 3, 4, 5)
    numbers.forEach {
        if (it == 3) return@forEach  // skip printing 3
        println(it)
    }
    println("Done")
}
Output
1 2 4 5 Done
⚠️

Common Pitfalls

A common mistake is using return inside a lambda without a label, which causes the enclosing function to return, not just the lambda. This can lead to unexpected behavior.

Wrong way (exits whole function):

kotlin
fun main() {
    val numbers = listOf(1, 2, 3)
    numbers.forEach {
        if (it == 2) return  // returns from main(), stops all processing
        println(it)
    }
    println("This will not print")
}
Output
1
📌

Right way (returns only from lambda):

kotlin
fun main() {
    val numbers = listOf(1, 2, 3)
    numbers.forEach {
        if (it == 2) return@forEach  // returns from lambda only
        println(it)
    }
    println("This will print")
}
Output
1 3 This will print

Key Takeaways

Use return@label to return from a lambda without exiting the outer function.
The last expression in a lambda is returned implicitly if no explicit return is used.
A plain return inside a lambda returns from the enclosing function, not just the lambda.
Label your lambdas or use standard labels like return@forEach to control flow clearly.
Understanding return behavior in lambdas helps avoid unexpected program exits.