How to Use Labeled Break in Kotlin: Simple Guide
In Kotlin, you use a
labeled break to exit from an outer loop or block by placing a label before the loop and using break with that label. This helps you stop nested loops early without extra flags or complicated logic.Syntax
A labeled break uses a label to identify which loop or block to exit. You define a label by writing an identifier followed by @ before the loop. Then, inside the nested loop, use break followed by the label to exit the labeled loop.
labelName@ for (item in collection) { ... }defines the label.break@labelNameexits the labeled loop.
kotlin
outer@ for (i in 1..3) { for (j in 1..3) { if (j == 2) break@outer println("i = $i, j = $j") } }
Output
i = 1, j = 1
Example
This example shows how to use a labeled break to exit an outer loop from inside an inner loop when a condition is met.
kotlin
fun main() {
outer@ for (i in 1..3) {
for (j in 1..3) {
if (j == 2) {
println("Breaking out of outer loop when j == 2")
break@outer
}
println("i = $i, j = $j")
}
}
println("Loops ended")
}Output
i = 1, j = 1
Breaking out of outer loop when j == 2
Loops ended
Common Pitfalls
One common mistake is forgetting to put the label before the loop you want to break out of, which causes a compile error. Another is using break without a label inside nested loops, which only breaks the innermost loop.
Also, labels must be unique in the scope and cannot be used with return or continue interchangeably.
kotlin
fun main() {
for (i in 1..3) {
inner@ for (j in 1..3) {
if (j == 2) {
// Wrong: break@outer (no label 'outer' defined)
// break@outer // This will cause a compile error
// Correct:
break@inner
}
println("i = $i, j = $j")
}
}
}Output
i = 1, j = 1
i = 1, j = 1
i = 1, j = 1
Quick Reference
| Concept | Usage | Description |
|---|---|---|
| Label Definition | labelName@ for (...) { ... } | Defines a label before a loop or block |
| Labeled Break | break@labelName | Exits the labeled loop or block immediately |
| Without Label | break | Exits only the innermost loop |
| Label Scope | Unique per scope | Labels must be unique and visible where used |
Key Takeaways
Use a label before a loop with
labelName@ to mark it for breaking.Use
break@labelName to exit the labeled loop from inside nested loops.Without a label,
break only exits the innermost loop.Labels must be defined in the same scope and be unique.
Labeled breaks help simplify exiting multiple nested loops cleanly.