Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A labeled break in Kotlin is a control flow construct that allows execution to jump out of a specific enclosing loop within a nested loop hierarchy. While a standard break expression implicitly terminates the nearest enclosing loop, a labeled break explicitly directs the compiler to terminate a targeted loop, transferring execution to the statement immediately following that labeled loop.

Syntax

A label is defined by an identifier followed immediately by the @ symbol, placed directly before the loop declaration. The break expression is invoked using the break keyword followed by @ and the identifier, with no whitespace.
labelName@ for (item in collection) {
    while (condition) {
        break@labelName
    }
}

Mechanics and Resolution

  • Label Declaration: Any valid Kotlin identifier can be used as a label (e.g., outer@, loopA@). The label is bound to the loop construct it precedes.
  • Invocation: When break@labelName is evaluated, it performs a local jump (compiled to a goto instruction in JVM bytecode) to exit the nested blocks. Because standard loops are local control flow structures, this operation does not involve unwinding the call stack.
  • Lexical Scoping: The label must reference an enclosing loop within the current lexical scope. A labeled break cannot target a loop in a separate function, a sibling loop, or an inner loop.
  • Execution Flow: Upon invocation, the targeted loop is immediately terminated. Any remaining iterations of both the inner loops and the targeted outer loop are discarded. Execution resumes at the first expression following the closing brace of the targeted loop.

Structural Example

The following demonstrates the execution flow when a labeled break is triggered:
outer@ for (i in 1..3) {
    for (j in 1..3) {
        if (i == 2 && j == 2) {
            // Terminates the loop labeled 'outer@'
            // A standard 'break' would only terminate the 'j' loop
            break@outer 
        }
        println("i=$i, j=$j")
    }
}
// Execution jumps directly here when break@outer is evaluated
println("Loop terminated")
Execution Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
Loop terminated
Master Kotlin with Deep Grasping Methodology!Learn More