Kotlin example

How to break out of nested loops in Kotlin

9 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Put a label on the outer loop and break to it: outer@ for (row in grid) { for (n in row) { if (n == 7) break@outer } }. A plain break leaves only the innermost loop, and continue@outer jumps to the next outer iteration. Since Kotlin 2.2, break and continue also work inside a forEach that sits in a loop; in a forEach on its own, return@forEach skips one element.

Kotlin has the labeled jumps you know from Java, spelled differently: Java's outer: becomes outer@, and break outer; becomes break@outer. The harder part is lambdas. forEach is a function call, not a loop, so break, continue and return inside it follow their own rules, and that is where most of the questions come from. The sections below cover labels, a function with return, break and continue inside forEach on current Kotlin, the compile error you get when there is no loop to leave, what return@forEach means, and the collection functions that make the loop unnecessary, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Labels: break@outer and continue@outerRecommended

A label is a name followed by @, written in front of a loop: outer@ for (…). Inside it, at any depth, break@outer ends that loop and continue@outer jumps to its next iteration. Without a label, break and continue act on the innermost loop around them. Labels work the same on while and do-while, and the name is yours to choose (rows@, search@).

LabeledBreak.kt
fun main() {
    val grid = listOf(
        listOf(3, 8, 1),
        listOf(9, 4, 7),
        listOf(5, 2, 6),
    )

    // A plain break leaves only the inner loop: the outer one goes on
    for (row in grid) {
        for (n in row) {
            if (n == 8) break
            println("plain: $n")
        }
    }

    // break@outer leaves both loops at once
    var found: Pair<Int, Int>? = null
    outer@ for ((r, row) in grid.withIndex()) {
        for ((c, n) in row.withIndex()) {
            if (n == 7) {
                found = r to c
                break@outer
            }
        }
    }
    println("7 at $found")

    // continue@rows skips the rest of the outer body too
    rows@ for (row in grid) {
        for (n in row) {
            if (n > 8) continue@rows
        }
        println("$row sums to ${row.sum()}")
    }
}

Output

The first loop shows the problem: break stops the row [3, 8, 1] at the 8, but the outer loop moves on and prints every number of the other two rows, from plain: 9 to plain: 6. break@outer ends both loops at the first 7 and prints 7 at (1, 2): row 1, column 2. In the last loop, continue@rows skips the println for the row that holds 9, so only [3, 8, 1] sums to 12 and [5, 2, 6] sums to 13 print. Without labels, both jobs need a flag variable checked after the inner loop.

2Move the loops into a function and return

When the nested loops are a search, put them in a function. return leaves every loop and the function in one step and hands back the result, so you need neither a label nor a var to carry the answer out (the found variable in section 1). The same works from inside forEach and forEachIndexed: they are inline functions, so a plain return in their lambda returns from the function that contains them. That is called a non-local return.

ReturnFromSearch.kt
data class Cell(val row: Int, val col: Int)

// return leaves every loop and the function in one step
fun find(grid: List<List<Int>>, target: Int): Cell? {
    for ((r, row) in grid.withIndex()) {
        for ((c, n) in row.withIndex()) {
            if (n == target) return Cell(r, c)
        }
    }
    return null
}

// return inside forEach works the same: forEach is inline
fun findWithForEach(grid: List<List<Int>>, target: Int): Cell? {
    grid.forEachIndexed { r, row ->
        row.forEachIndexed { c, n ->
            if (n == target) return Cell(r, c)
        }
    }
    return null
}

fun main() {
    val grid = listOf(
        listOf(3, 8, 1),
        listOf(9, 4, 7),
        listOf(5, 2, 6),
    )
    println(find(grid, 7))
    println(find(grid, 10))
    println(findWithForEach(grid, 2))
}

Output

find(grid, 7) gives Cell(row=1, col=2), a target that is not there gives null, and the forEachIndexed version finds 2 at Cell(row=2, col=1). The return type Cell? puts the not-found case in the signature, and callers deal with it through ?: or ?.let (see check for null). If the loops do one job, this is usually the cleanest form.

3break and continue inside forEach (Kotlin 2.2)

For years, break and continue inside a forEach did not compile at all. Kotlin 2.2 made non-local break and continue stable: inside the lambda of an inline function such as forEach, forEachIndexed or repeat, they act on the nearest loop around the call. Here they compile with no flag. Read that rule closely: continue moves the loop to its next iteration, not the forEach to its next element. A label picks a loop further out, which matters when the lambda holds a loop of its own.

ForEachBreak.kt
fun main() {
    val batches = listOf(
        listOf(12, 15, 11),
        listOf(14, -1, 13),
        listOf(16, 99, 10),
        listOf(18, 17, 19),
    )

    for ((i, batch) in batches.withIndex()) {
        var total = 0
        batch.forEach { reading ->
            if (reading < 0) {
                println("batch $i: bad reading, skipped")
                continue // goes to the next batch
            }
            if (reading == 99) {
                println("batch $i: stop code")
                break // leaves the for loop
            }
            total += reading
        }
        println("batch $i: total $total")
    }

    // With a loop inside the lambda, a label picks the outer one
    val limits = listOf(20, 15)
    outer@ for (batch in batches) {
        batch.forEach { reading ->
            for (limit in limits) {
                if (reading > limit) continue@outer
            }
        }
        println("every reading within $limits: $batch")
    }
}

Output

Batch 0 adds up to batch 0: total 38. In batch 1, continue at the -1 skips the rest of the batch and its total line too, and the loop moves to batch 2. There, break at the 99 leaves the for, so batch 3 is never read. In the second loop, a plain continue inside for (limit in limits) would only move to the next limit; continue@outer skips to the next batch, so only the two batches with no reading above 15 print. On a project older than Kotlin 2.2, use the forms in section 5 instead.

4break in a forEach with no loop: the compile error

The new rule has a limit: break and continue still need a real loop to act on. A forEach is a function call, so a break inside a forEach that no loop surrounds has nothing to leave, and the program below does not compile. It is the code most people write first when they want to stop a forEach early.

LoneForEach.kt
fun main() {
    val words = listOf("apple", "banana", "STOP", "cherry")

    words.forEach { w ->
        if (w == "STOP") break
        println(w)
    }
}

Output

The compiler stops with 'break' and 'continue' are only allowed inside loops. In a lambda passed to a function that is not inline, such as a Runnable, the error is different even inside a loop: 'break' or 'continue' crosses a function or class boundary. That lambda could run later, after the loop has finished. To make the program above work, change line 4 to for (w in words) and keep the break, wrap the forEach in run as in the next section, or let takeWhile do the stopping (section 6).

5return@forEach and run loop@: what return@ means

return@label returns from the lambda that carries the label, not from the function around it. Every lambda passed to a function gets an implicit label named after that function, so return@forEach ends the current call of the forEach lambda and the forEach goes on with the next element: it acts like continue. To act like break, the return has to leave something that wraps the whole forEach: put it in run loop@{ … } and write return@loop. You can name a lambda's label yourself (forEach word@{ … }), and return@map -1 makes -1 the lambda's value for that element. A plain return with no label does something else: it leaves the whole enclosing function. These forms work on every Kotlin version.

ReturnAtLabel.kt
fun printUntilStop(words: List<String>) {
    words.forEach { w ->
        if (w == "STOP") return // leaves printUntilStop, not the lambda
        println("plain return: $w")
    }
    println("never printed")
}

fun main() {
    val words = listOf("apple", "", "banana", "STOP", "cherry")

    // return@forEach ends this call of the lambda: works like continue
    val kept = mutableListOf<String>()
    words.forEach { w ->
        if (w.isEmpty()) return@forEach
        kept += w
    }
    println(kept)

    // A label on run: return@loop leaves the whole forEach, like break
    val beforeStop = mutableListOf<String>()
    run loop@{
        words.forEach { w ->
            if (w == "STOP") return@loop
            beforeStop += w
        }
    }
    println(beforeStop)

    // Name the lambda's label yourself
    val long = mutableListOf<String>()
    words.forEach word@{ w ->
        if (w.length < 6) return@word
        long += w
    }
    println(long)

    // return@map gives the lambda's value for this element
    val lengths = words.map { w ->
        if (w.isEmpty()) return@map -1
        w.length
    }
    println(lengths)

    printUntilStop(listOf("one", "two", "STOP", "three"))
    println("back in main")
}

Output

return@forEach skips the empty string and nothing else: [apple, banana, STOP, cherry]. return@loop stops at STOP, so beforeStop holds [apple, , banana] (this block keeps the empty string). The map line gives -1 for the empty word: [5, -1, 6, 4, 6]. printUntilStop prints two words, then its plain return leaves the function at STOP, so never printed never shows and the program goes on with back in main. In a lambda passed to a function that is not inline, a plain return does not compile; here the error reads 'return' is prohibited here.

6any, firstOrNull and takeWhile instead of a loop

Most nested loops that need a break are searches, and the collection functions already search and stop at the answer. any, all and none return a Boolean; firstOrNull returns the first match or null; firstNotNullOfOrNull runs a lambda on each element and returns the first result that is not null, which lets an inner search report out of an outer one. takeWhile keeps elements until the first one that fails. With these there is no loop to break out of. Coming from Java streams: any is anyMatch and firstOrNull is findFirst.

SearchFunctions.kt
fun main() {
    val grid = listOf(
        listOf(3, 8, 1),
        listOf(9, 4, 7),
        listOf(5, 2, 6),
    )

    // any stops at the first match, in both lists
    var checks = 0
    val hasBig = grid.any { row -> row.any { checks++; it > 8 } }
    println("any > 8: $hasBig after $checks checks")

    // all, none and firstOrNull stop early the same way
    println(grid.all { row -> row.none { it == 0 } })
    println(grid.firstOrNull { row -> 7 in row })

    // The first match across nested lists, or null
    println(grid.firstNotNullOfOrNull { row -> row.firstOrNull { it > 7 } })
    println(grid.firstNotNullOfOrNull { row -> row.firstOrNull { it > 9 } })

    // Its position: the row and column of the first 7
    val at = grid.withIndex().firstNotNullOfOrNull { (r, row) ->
        row.indexOf(7).takeIf { it >= 0 }?.let { c -> r to c }
    }
    println(at)

    // takeWhile keeps elements until the first one that fails
    val readings = listOf(12, 15, 11, 99, 14)
    println(readings.takeWhile { it != 99 })
}

Output

The counter shows that any stops: it looked at 3, 8, 1 and 9, then printed any > 8: true after 4 checks without touching the other five numbers. firstOrNull { row -> 7 in row } gives the whole row [9, 4, 7], while firstNotNullOfOrNull gives the number itself, 8, or null when nothing is above 9. The position search prints (1, 2), the same answer as break@outer in section 1, with no var and no label. takeWhile cuts the list at the 99: [12, 15, 11].

7Which should you use?

MethodStopsWorks inBest for
break@outer / continue@outerAny loop you labelfor, while, do-whileNested loops with more work after the search
return from a functionEvery loop at onceLoops and inline lambdasSearches that hand back a result
any / firstOrNull / takeWhileAt the first matchCollections and sequencesChecking, finding or cutting without a loop
break / continue in forEachThe loop around itInline lambdas inside a loop, Kotlin 2.2+forEach code that already sits in a loop
return@forEachThis element onlyAny lambdacontinue in a forEach, every Kotlin version
run loop@{ … return@loop }The whole forEachInline lambdasbreak in a forEach on Kotlin before 2.2

Frequently asked questions

What does return@ mean in Kotlin?

return@label returns from the lambda marked with that label instead of from the enclosing function. A lambda gets an implicit label named after the function it is passed to, so inside list.forEach { … }, return@forEach ends the current call of the lambda and the forEach moves on to the next element. You can name a label yourself, as in list.forEach item@{ … return@item }, and give a value: return@map -1 makes -1 the result for that element. With nested forEach calls, return@forEach refers to the innermost one.

How do I break out of a forEach in Kotlin?

If the forEach sits inside a for or while loop, Kotlin 2.2 and later accept break in it, and it ends that loop. A forEach on its own cannot be broken: break there gives 'break' and 'continue' are only allowed inside loops. Write a for loop instead, wrap the forEach in run loop@{ … } and return@loop, or use takeWhile, firstOrNull or any, which stop by themselves.

How do I continue to the next element in a forEach?

Use return@forEach: it skips the rest of the lambda for the current element, which is what continue does in a loop. Since Kotlin 2.2 a plain continue inside a forEach compiles too, but it moves the loop around the forEach to its next iteration, not the forEach to its next element, so it skips every remaining element of that forEach.

Why does return inside forEach exit my whole function?

forEach is an inline function, so a plain return in its lambda is a non-local return: it returns from the function that contains the forEach and skips everything after it. Use return@forEach to leave only the lambda. In a lambda passed to a function that is not inline, a plain return does not compile and the error reads 'return' is prohibited here.

Does break leave all nested loops in Kotlin?

No. A plain break ends only the innermost loop around it, and the outer loop goes on with its next iteration. Label the outer loop (outer@ for (…)) and write break@outer to end both, or move the loops into a function and return.

Can I use break and continue inside when in a loop?

Yes. Since Kotlin 1.4, a break or continue inside a when that sits in a loop acts on the loop, with no label needed: in for (i in 1..5) { when { i == 2 -> continue; i == 4 -> break } } the continue skips to the next i and the break ends the loop.

Which Kotlin version allows break and continue in lambdas?

Non-local break and continue became stable in Kotlin 2.2. Kotlin 2.1 had them as a preview behind the -Xnon-local-break-continue compiler flag, and older versions reject them. They only work in lambdas passed to inline functions such as forEach and repeat. On older projects, use return@forEach for continue and run loop@{ … return@loop } for break.

Run it yourself

Open any of these in the full Kotlin editor to tweak, run and share.

Kotlin playground