0
0
Kotlinprogramming~7 mins

Labeled break and continue in Kotlin

Choose your learning style9 modes available
Introduction

Labeled break and continue help you control loops more precisely when you have nested loops.

When you want to stop an outer loop from inside an inner loop.
When you want to skip to the next iteration of an outer loop from inside an inner loop.
When you have multiple loops inside each other and need clear control over which loop to break or continue.
When normal break or continue only affects the closest loop but you want to affect a specific outer loop.
Syntax
Kotlin
label@ for (item in collection) {
    // code
    break@label  // stops the loop labeled 'label'
    continue@label  // skips to next iteration of loop labeled 'label'
}

The label is a name you give to a loop followed by @.

You use break@label or continue@label to control that specific loop.

Examples
This stops the outer loop when j equals 2.
Kotlin
outer@ for (i in 1..3) {
    for (j in 1..3) {
        if (j == 2) break@outer
        println("i = $i, j = $j")
    }
}
This skips to the next iteration of the outer loop when j equals 2.
Kotlin
outer@ for (i in 1..3) {
    for (j in 1..3) {
        if (j == 2) continue@outer
        println("i = $i, j = $j")
    }
}
Sample Program

This program prints pairs of i and j. When j equals 2, it breaks the outer loop labeled 'outer', stopping all loops.

Kotlin
fun main() {
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (j == 2) {
                println("Breaking outer loop when i=$i and j=$j")
                break@outer
            }
            println("i = $i, j = $j")
        }
    }
}
OutputSuccess
Important Notes

Labels must be placed before the loop you want to control.

Using labeled break or continue makes your code clearer when working with nested loops.

Don't overuse labels; sometimes refactoring loops can be simpler.

Summary

Labeled break and continue let you control specific loops in nested loops.

Use break@label to stop a labeled loop.

Use continue@label to skip to the next iteration of a labeled loop.