What if you could instantly jump out of any loop you want, no matter how deep it is?
Why Labeled break and continue in Kotlin? - Purpose & Use Cases
Imagine you are cooking multiple dishes at once, and you need to stop cooking one dish immediately when a certain ingredient is missing, but continue cooking the others. Doing this without clear signals can get confusing fast.
Without labeled break and continue, you might have to write complicated checks and flags to control which loop to stop or continue. This makes your code messy, hard to read, and easy to make mistakes.
Labeled break and continue let you clearly say which loop to stop or skip to the next iteration. This keeps your code clean and your intentions clear, just like using labels on your cooking pots to know exactly which one to handle.
for (i in 1..3) { for (j in 1..3) { if (someCondition) break } }
outer@ for (i in 1..3) { for (j in 1..3) { if (someCondition) break@outer } }
You can precisely control complex nested loops, making your code easier to understand and maintain.
When searching for a specific item in a grid, labeled break lets you stop searching immediately once found, without extra checks.
Labeled break and continue help manage nested loops clearly.
They prevent messy and error-prone manual checks.
They make your code cleaner and easier to follow.