0
0
Kotlinprogramming~3 mins

Why Labeled break and continue in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could instantly jump out of any loop you want, no matter how deep it is?

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
for (i in 1..3) {
  for (j in 1..3) {
    if (someCondition) break
  }
}
After
outer@ for (i in 1..3) {
  for (j in 1..3) {
    if (someCondition) break@outer
  }
}
What It Enables

You can precisely control complex nested loops, making your code easier to understand and maintain.

Real Life Example

When searching for a specific item in a grid, labeled break lets you stop searching immediately once found, without extra checks.

Key Takeaways

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.