Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 134 ยท Control Flow

break, continue and Labels

Learn how break and continue work in Kotlin, how labeled loops escape nested loops, how return@label works in lambdas, and what non-local break and continue in inline lambdas do.

Most loops do not run from start to finish without interruption. You stop as soon as you find what you were looking for, or you skip the items that do not interest you. Kotlin gives you break and continue for that, plus labels, which let you aim them at an outer loop. It also has return@label, the same idea applied to lambdas. Labels look unusual at first, with their @ signs, but they follow one simple rule that this lesson spells out.

If you have not read Loops yet, start there: this lesson assumes you know for, while and ranges.

break: leave the loop

break ends the innermost enclosing loop immediately. The program continues with the first statement after the loop.

Kotlin Stopping when you find it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Without break the loop would look at every element, even after the answer is known. For short lists nobody cares, but the habit matters for big inputs. For this particular job a collection function says it more clearly, temperatures.indexOfFirst { it > 30 }, and you should reach for it when it fits. A break is the right tool when the loop body does several things, or when you have a while (true) loop that you leave from the middle.

Kotlin while (true) with a break in the middle

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice ?: break. In Kotlin break, continue and return are expressions of type Nothing: they never produce a value, because control leaves before there is one. That means you can put them on the right-hand side of the Elvis operator ?:, which reads nicely as "take the next message, or stop if there is none". More about Nothing in Any, Unit and Nothing.

continue: skip to the next iteration

continue abandons the current pass of the innermost loop and jumps to the next one. In a for loop it takes the next element; in a while loop it re-checks the condition.

Kotlin Skipping unwanted items

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The pattern "check the uninteresting cases first and continue" keeps the main logic at one indentation level instead of nesting it inside an if. These early-exit lines are called guard clauses, and they make loops easier to read once there are three or four conditions.

In a while loop, continue jumps straight back to the condition. If you increment your counter after the continue, the increment is skipped and the loop may never end. Update the counter before the continue, or use a for loop.

The problem with nested loops

Both break and continue only affect the innermost loop. That is a problem when you are searching a grid and want to stop everything the moment you find the item:

Kotlin break only leaves the inner loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

You will see that after found 5, breaking the loop still visits 7, 8 and 9: the break ended the inner loop over [4, 5, 6], but the outer loop carried on with the third row. Languages solve this in different ways, with flags, exceptions or goto. Kotlin's answer is labels.

Labels: naming a loop

A label is an identifier followed by @, written in front of an expression. Put it before a loop, then say break@label or continue@label to target that exact loop.

Kotlin Breaking out of both loops

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The label search@ is attached to the outer for. break@search ends that loop, no matter how deeply nested the break is. Use continue@label the same way when you want the outer loop to move on to its next item:

Kotlin continue to the outer loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Here the inner loop looks for a divisor. As soon as it finds one, continue@outer abandons the inner loop and skips the "is prime" line for this n. Without the label you would need a boolean flag such as isPrime, which works but is easier to get wrong.

Some points about the syntax:

  • There is no space between the name and @ when you define a label (outer@ for), and none between break and @name when you use it (break@outer).
  • Label names are your choice. Short, descriptive names such as outer, rows or search read best.
  • If a function has a nested loop that needs labels in several places, that is often a signal to move the inner part into its own function and use return.

Extracting the search into a function is frequently clearer than a label: fun findPosition(grid: List<List<Int>>, target: Int): Pair<Int, Int>? can simply return as soon as it finds the target, from any depth, with no label at all.

Labels with return: return@label

The same @label idea applies to lambdas, the pieces of code in braces that you pass to functions such as forEach. A plain return inside a lambda normally returns from the enclosing function (when the function taking the lambda is inline, which forEach is). To return from just the lambda, you label it:

Kotlin return from the enclosing function vs return@forEach

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In firstNegative, return it leaves the whole function with a result as soon as a negative number appears. In printNonNegative, return@forEach only ends the current call of the lambda, which behaves exactly like continue in a loop: the next element is processed, and finished printing is still printed.

Every lambda passed to a function gets an implicit label with the name of that function, so return@forEach, return@map and return@filter work without any declaration. You can also write your own label in front of the lambda:

Kotlin Naming your own lambda label

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice that return@map -1 returns a value from the lambda, which becomes that element of the result. Without a label, return -1 inside a map lambda would try to return from main, which returns Unit, and the compiler would reject it.

Non-local break and continue

Here is a detail that changed in recent Kotlin versions. For a long time you could not use break or continue inside a forEach lambda, even if the lambda sat inside a for loop; the compiler rejected it. Since Kotlin 2.2 this is stable: if the function that receives the lambda is inline (as forEach, map, filter, let and repeat are), then break and continue inside the lambda affect the surrounding loop, exactly like a non-local return.

Kotlin break and continue inside an inline lambda

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

There is no loop inside the lambda, so the continue targets the surrounding for (batch in batches). The run shows negative value -1, skipping the batch and then goes straight to the third batch, without printing value 6 and without printing end of batch for the second batch. That surprises people who expect continue to skip only one element of forEach. If you want that behavior, use return@forEach, or better, a plain for loop.

Because continue inside an inline lambda targets the enclosing loop, the same code means something different depending on whether a loop is around it. Mixing forEach with break and continue is legal, but it is hard to read. When a loop needs early exits, write a normal for loop.

This only works because the lambda is inlined into the loop at compile time. For a function that is not inline, the lambda is a separate object, and a break or continue inside it is a compile error:

Kotlin break in a non-inline lambda (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The compiler stops with main.kt:9:25: error: 'break' or 'continue' crosses a function or class boundary. Declare runTwice as inline and the code compiles, because the lambda becomes part of the loop. The details of inline come in Inline Functions.

Choosing the right tool

You want to... Use
Stop the innermost loop break
Skip to the next item in the innermost loop continue
Stop or skip an outer loop break@label, continue@label
Leave the function with a result return (works from any loop depth)
End a lambda's current call return@name
Find an element or answer a yes/no question first { }, find { }, any { }, indexOfFirst { }

Labeled loops are a precise tool, not a style to use everywhere. Most of the time one of the collection functions in the last row, or a function that returns early, will be shorter and safer.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a nested for loop, which loop does a plain break end?

    break (and continue) always target the innermost enclosing loop unless you add a label such as break@outer.
  2. 2. What does continue@outer do inside an inner loop whose outer loop is labeled outer@?

    continue@outer jumps to the next iteration of the labeled loop, ending the inner loop immediately.
  3. 3. Inside list.forEach { ... }, what does return@forEach do?

    return@forEach returns from the lambda only, which acts like continue; the following elements are still processed.
  4. 4. Why can val x = queue.removeFirstOrNull() ?: break compile?

    break, continue and return never produce a value; their type is Nothing, which is a subtype of every type, so the expression type-checks.
  5. 5. When is break allowed inside a lambda, in Kotlin 2.2 and later?

    Non-local break and continue are stable since Kotlin 2.2, but only for lambdas inlined into an enclosing loop.

Summary

  • break leaves the innermost loop; continue skips to its next iteration.
  • Both are expressions of type Nothing, so ?: break and ?: continue are common idioms.
  • Name a loop with label@ for ... and use break@label or continue@label to affect an outer loop.
  • return@name returns from a lambda; every lambda has an implicit label named after the function it is passed to.
  • Since Kotlin 2.2, break and continue work inside lambdas of inline functions and affect the surrounding loop; they are errors in non-inline lambdas.
  • Often a collection function (firstOrNull, any) or an early return from a small function is clearer than a labeled loop.

Next: Ranges and Progressions