Non-local break and continue
suggest changeSince Kotlin 2.2 you can use break and continue inside a lambda passed to an inline function, such as forEach, let, use or repeat, when that lambda is inside a loop. The jump goes to the enclosing for, while or do-while loop, the same as if the code weren't in a lambda.
Before 2.2 this was a compile error, and you had to use return@forEach, run blocks with labels, or rewrite the code as a plain loop.
| Kotlin version | Status |
|---|---|
| 2.1 | preview, needs -Xnon-local-break-continue |
| 2.2 | stable, on by default |
| 2.4 | stable; the old flag is reported as redundant |
All examples were compiled and run with Kotlin 2.4.21 on JDK 25.
For break and continue in ordinary loops, see Break and continue.
A first example
Scope functions like let are often used inside loops to deal with nullable values. You can now leave the current iteration or the whole loop from inside them:
data class Order(val id: Int, val customer: String?, val total: Int)
fun main() {
val orders = listOf(
Order(1, "ann", 120),
Order(2, null, 40),
Order(3, "bob", 0),
Order(4, "cy", 75),
Order(5, "dee", -1),
Order(6, "eve", 30),
)
var revenue = 0
for (order in orders) {
order.customer?.let { name ->
if (order.total == 0) continue // skip free orders
if (order.total < 0) {
println("bad total in order ${order.id}, stopping")
break // stop processing
}
println("$name paid ${order.total}")
revenue += order.total
}
}
println("revenue: $revenue")
}
Output:
ann paid 120
cy paid 75
bad total in order 5, stopping
revenue: 195
continue and break here belong to the for (order in orders) loop. let is an inline function, so the compiler copies the lambda's body into the loop, and the jumps are compiled to ordinary jump instructions. No exceptions or extra objects are involved.
With language version 2.1 or older the same code doesn't compile:
$ kotlinc orders.kt -language-version 2.1
warning: language version 2.1 is deprecated and its support will be removed in a future version of Kotlin. Update the version to 2.2.
orders.kt:15:35: error: the feature "break continue in inline lambdas" is only available since language version 2.2
if (order.total == 0) continue // skip free orders
^^^^^^^^
orders.kt:18:17: error: the feature "break continue in inline lambdas" is only available since language version 2.2
break // stop processing
^^^^^
On Kotlin 2.1 you could turn it on with -Xnon-local-break-continue. On 2.2 and newer you don't need any flag, and 2.4 warns if you still pass it:
warning: the argument '-Xnon-local-break-continue' is redundant for the current language version 2.4.
Lambdas that return values
break and continue have the type Nothing, the same as return and throw. That means you can use them anywhere a value is expected, including on the right side of ?: inside a map lambda:
fun main() {
val rows = listOf("1,2,3", "4,x,6", "7,8,9")
for (row in rows) {
val numbers = row.split(",").map { it.toIntOrNull() ?: continue }
println("$row -> sum ${numbers.sum()}")
}
val report = buildString {
for (n in 1..10) {
if (n % 4 == 0) continue
append(n).append(' ')
if (length > 10) break
}
}
println(report)
}
Output:
1,2,3 -> sum 6
7,8,9 -> sum 24
1 2 3 5 6 7
The row 4,x,6 is skipped as soon as map sees x; the rest of that row isn't parsed. The second half shows the opposite nesting: the loop is inside the buildString lambda, so break and continue are plain local jumps, which always worked.
Careful with forEach: the jump targets the outer loop
forEach is itself a loop, but it's a function, not a loop statement. break and continue inside its lambda don't affect forEach. They go to the nearest enclosing for, while or do-while:
fun main() {
val batches = listOf(listOf(1, 2, -3, 4), listOf(5, 6), listOf(7, 0, 8))
for ((i, batch) in batches.withIndex()) {
batch.forEach { n ->
if (n < 0) continue // next batch, not next number
if (n == 0) break // leaves the for loop
println("batch $i: $n")
}
println("batch $i done")
}
println("finished")
}
Output:
batch 0: 1
batch 0: 2
batch 1: 5
batch 1: 6
batch 1 done
batch 2: 7
finished
When -3 is found, continue skips the remaining number 4 and the line batch 0 done, and moves to the next batch. When 0 is found, break ends the whole for loop.
The same applies to repeat, forEachIndexed, onEach and other iterating inline functions. If you want "skip this element" semantics, use a for loop over the collection, or return@forEach (described below).
Without an enclosing loop statement, break and continue in a forEach are still an error:
listOf(1, 2).forEach { if (it == 2) break }
error: 'break' and 'continue' are only allowed inside loops.
You also can't use the lambda's label as a loop label. continue@forEach is rejected even inside a loop:
error: label does not denote a reachable loop.
Labels
Labeled break@label and continue@label work across lambdas too. This is useful when the lambda is inside several loops:
fun main() {
val grid = listOf(
listOf(3, 8, 1),
listOf(9, 4, 7),
listOf(2, 6, 5),
)
// find the first row containing a value > 8
outer@ for ((r, row) in grid.withIndex()) {
row.forEachIndexed { c, v ->
if (v > 8) {
println("found $v at ($r, $c)")
break@outer
}
}
}
// labeled continue across two levels of loops
val words = listOf("kotlin", "java", "rust", "go")
words@ for (w in words) {
for (other in words) {
if (other == w) continue
other.forEach { ch ->
if (ch in w) {
println("$w shares '$ch' with $other")
continue@words
}
}
}
println("$w shares nothing")
}
}
Output:
found 9 at (1, 0)
kotlin shares 't' with rust
java shares nothing
rust shares 't' with kotlin
go shares 'o' with kotlin
In the second loop, plain continue inside forEach would go to the inner for (other in words) loop. continue@words skips to the next word of the outer loop.
Resources, locks and try/finally
Inline functions that wrap their lambda in try/finally still run the finally block when you jump out with break or continue. This makes the feature safe to use with use, withLock and synchronized.
Here use closes each reader even when the loop leaves the lambda early:
import java.io.File
fun main() {
val dir = File("logs").apply { mkdirs() }
File(dir, "a.log").writeText("INFO start\nERROR disk full\nINFO retry\n")
File(dir, "b.log").writeText("INFO ok\nINFO ok\n")
File(dir, "c.log").writeText("FATAL crash\nINFO never read\n")
for (file in dir.listFiles()!!.sortedBy { it.name }) {
file.bufferedReader().use { reader ->
reader.lineSequence().forEach { line ->
if (line.startsWith("FATAL")) {
println("${file.name}: $line - giving up")
break
}
if (line.startsWith("ERROR")) {
println("${file.name}: $line")
continue // rest of this file is not interesting
}
}
println("${file.name}: clean")
}
}
}
Output:
a.log: ERROR disk full
b.log: clean
c.log: FATAL crash - giving up
Note that lineSequence() returns a Sequence, and Sequence.forEach is inline too, so the jump passes through two inline lambdas (forEach and use).
A queue consumer with a lock, and a retry loop using runCatching:
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
val lock = ReentrantLock()
val queue = ArrayDeque(listOf("a", "b", "stop", "c"))
fun flaky(attempt: Int): String =
if (attempt < 3) error("timeout #$attempt") else "response"
fun main() {
while (true) {
lock.withLock {
val item = queue.removeFirstOrNull() ?: break
if (item == "stop") break
println("took $item")
}
}
println("lock held after loop: ${lock.isLocked}, left: $queue")
var result: String? = null
for (attempt in 1..5) {
runCatching { flaky(attempt) }
.onSuccess { result = it; break }
.onFailure { println("attempt $attempt failed: ${it.message}") }
}
println("result: $result")
}
Output:
took a
took b
lock held after loop: false, left: [c]
attempt 1 failed: timeout #1
attempt 2 failed: timeout #2
result: response
withLock unlocks in its finally block, so the lock is released after break. onSuccess and onFailure are inline, so break in onSuccess ends the retry loop.
Your own inline functions
Any inline function with a regular (not noinline or crossinline) function parameter supports break and continue in its lambda. You don't need contracts or annotations.
Keep in mind that a jump skips the rest of the inline function body, just like a non-local return does. Code after block() only runs if the lambda finishes normally:
inline fun step(label: String, block: () -> Unit) {
println("start $label")
block()
println("end $label")
}
fun main() {
for (size in listOf(10, 0, 3)) {
step("size $size") {
if (size == 0) continue
println(" sum = ${List(size) { it * it }.sum()}")
}
}
}
Output:
start size 10
sum = 285
end size 10
start size 0
start size 3
sum = 5
end size 3
There's no end size 0. If your function must always do something after the lambda (close, unlock, log, measure), put it in finally:
inline fun <T> traced(name: String, block: () -> T): T {
println("enter $name")
try {
return block()
} finally {
println("exit $name")
}
}
fun main() {
for (i in 1..3) {
traced("step $i") {
if (i == 2) continue
if (i == 3) break
println("working on $i")
}
}
}
Output:
enter step 1
working on 1
exit step 1
enter step 2
exit step 2
enter step 3
exit step 3
More about inlining in Inline Functions.
Where it doesn't work
The lambda must be inlined into the function that contains the loop. If it's compiled into a separate object, it may run later or on another thread, when the loop no longer exists. So the compiler rejects jumps from:
- lambdas passed to non-inline functions
crossinlineandnoinlineparameters of inline functions- lambdas stored in variables
- non-inline library functions such as
Sequence.map,Thread {}, coroutine builders likelaunch, and SAM conversions to Java interfaces
fun runLater(block: () -> Unit) = block()
inline fun runInline(crossinline block: () -> Unit) {
val r = Runnable { block() }
r.run()
}
inline fun twoBlocks(a: () -> Unit, noinline b: () -> Unit) { a(); b() }
fun main() {
for (i in 1..3) {
runLater { if (i == 2) break }
runInline { if (i == 2) continue }
twoBlocks({ if (i == 1) continue }, { if (i == 2) break })
val f = { if (i == 2) break }
sequenceOf(1, 2).map { if (it == 2) continue; it }.toList()
Thread { if (i == 2) break }
}
}
Every line in the loop except the first lambda of twoBlocks is rejected:
err.kt:11:32: error: 'break' or 'continue' crosses a function or class boundary.
runLater { if (i == 2) break }
^^^^^
err.kt:12:33: error: 'break' or 'continue' crosses a function or class boundary.
runInline { if (i == 2) continue }
^^^^^^^^
err.kt:13:59: error: 'break' or 'continue' crosses a function or class boundary.
twoBlocks({ if (i == 1) continue }, { if (i == 2) break })
^^^^^
err.kt:14:31: error: 'break' or 'continue' crosses a function or class boundary.
val f = { if (i == 2) break }
^^^^^
err.kt:15:45: error: 'break' or 'continue' crosses a function or class boundary.
sequenceOf(1, 2).map { if (it == 2) continue; it }.toList()
^^^^^^^^
err.kt:16:30: error: 'break' or 'continue' crosses a function or class boundary.
Thread { if (i == 2) break }
^^^^^
Sequence.map isn't inline because a sequence is lazy: the lambda runs later, when toList() pulls elements. Iterable.map and Sequence.forEach are inline, so they work.
A subtle case is Map.forEach. With a destructured pair { (k, v) -> } you call Kotlin's inline extension. With two parameters { k, v -> } you call Java's Map.forEach(BiConsumer), which isn't inline:
fun main() {
val stock = mapOf("apple" to 3, "pear" to 0, "plum" to 5)
for (shop in listOf("north", "south")) {
stock.forEach { (fruit, count) -> // Kotlin's inline forEach
if (count == 0) continue
println("$shop: $fruit")
}
stock.forEach { fruit, count -> // java.util.Map.forEach(BiConsumer)
if (count == 0) continue
}
}
}
ex10.kt:9:29: error: 'break' or 'continue' crosses a function or class boundary.
if (count == 0) continue
^^^^^^^^
If one of your own helpers triggers this error and doesn't store the lambda, the fix is usually to mark it inline.
The old workarounds
Before Kotlin 2.2, code that needed to skip or stop inside forEach used labeled returns:
fun main() {
val ids = listOf(1, 2, 3, 4, 5)
// old: continue -> return@forEach
ids.forEach {
if (it % 2 == 0) return@forEach
print("$it ")
}
println()
// old: break -> return from a labeled run block
run loop@{
ids.forEach {
if (it > 3) return@loop
print("$it ")
}
}
println()
// simplest: a for loop
for (it in ids) {
if (it > 3) break
print("$it ")
}
println()
}
Output:
1 3 5
1 2 3
1 2 3
return@forEach still has its place: it's the only way to skip to the next element of forEach itself, because non-local continue goes to the enclosing loop. The run loop@{ ... return@loop } trick for breaking out of forEach is no longer needed when there's a real loop around it, and when there isn't, a for loop is clearer.
Code that worked around the restriction in other ways can often be simplified on Kotlin 2.2+:
| Before 2.2 | Kotlin 2.2+ |
|---|---|
a var skip = false flag set inside let, checked after it |
continue directly inside let |
a var found = false flag set in forEach, checked after it |
break@outer inside forEach |
rewriting runCatching { }.onSuccess { } as try/catch to break out of a retry loop |
break in onSuccess |
See Functional constructs for iteration for more on forEach and related functions, and Loops in Kotlin for loop basics.