Kotlin Tutoial

Basics

Control Flow

Array & String

Functions

Collections

OOPs Concept

Exception Handling

Null Safety

Regex & Ranges

Java Interoperability

Miscellaneous

Android

Kotlin labeled break

In Kotlin, like many other languages, the break statement is used to terminate the nearest enclosing loop (i.e., for, while, or do-while). But what if you are working with nested loops and you wish to break out of an outer loop from within an inner loop? That's where the labeled break comes in handy.

Here's a tutorial on Kotlin's labeled break:

1. Basic Use of break:

In a single loop, you can use break to exit the loop.

for (i in 1..10) {
    if (i == 5) break
    print(i)  // Outputs: 1234
}

2. Using Labels:

In Kotlin, you can label loops (and other expressions as well) and then use that label to specify which loop you want to break out of.

outerLoop@ for (i in 1..5) {
    for (j in 1..5) {
        print("$i$j ")
        if (i == 3 && j == 3) break@outerLoop
    }
    println()
}

In the above example, when i is 3 and j is 3, the break statement will terminate the outerLoop, not just the inner loop.

3. Labeled continue:

Similarly, Kotlin allows you to use labeled continue statements. The continue statement skips the current iteration of the loop and continues with the next iteration. With labeled continue, you can specify which loop's current iteration you wish to skip.

outerLoop@ for (i in 1..5) {
    for (j in 1..5) {
        if (j == 3) continue@outerLoop
        print("$i$j ")
    }
    println()
}

In this example, when j is 3, the continue@outerLoop statement is executed, causing the current iteration of the outerLoop to be skipped, and the next iteration of the outerLoop to start.

4. Not Just for Loops:

While the labeled break and continue statements are often used with loops, labels in Kotlin can be applied to other expressions as well. This can be useful in lambdas, for example.

5. Avoid Overusing Labels:

While labeled breaks and continues are powerful, it's essential to use them judiciously. Overuse can lead to code that's hard to read and maintain. If you find yourself using them frequently, consider refactoring your code or breaking it into smaller functions.

Conclusion:

Labeled break and continue in Kotlin allow for more precise control flow within nested loops or when working with other labeled expressions. Understanding how and when to use them can be a valuable tool in your Kotlin programming toolkit.

  1. Using labels with break in Kotlin:

    • Labels provide a way to name loops and control statements for more fine-grained control.
    outer@ for (i in 1..5) {
        for (j in 1..5) {
            if (j == 3) {
                break@outer  // Breaks out of the outer loop
            }
            println("i: $i, j: $j")
        }
    }
    
  2. Breaking out of nested loops with labels in Kotlin:

    • Labels allow breaking out of specific nested loops.
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                break@outer  // Breaks out of the outer loop when i=2 and j=2
            }
            println("i: $i, j: $j")
        }
    }
    
  3. Labeled breaks vs regular breaks in Kotlin:

    • Labeled breaks provide more control over which loop to break out of, compared to regular breaks.
    for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                break  // Regular break, breaks out of the inner loop only
            }
            println("i: $i, j: $j")
        }
    }
    
  4. Labeling and scoping in Kotlin break statements:

    • Labels are scoped to the nearest enclosing loop, making it clear which loop is affected.
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            inner@ for (k in 1..3) {
                if (k == 2) {
                    break@outer  // Breaks out of the outermost loop
                }
                println("i: $i, j: $j, k: $k")
            }
        }
    }
    
  5. Error handling with labeled breaks in Kotlin:

    • Labeled breaks can be used for error handling scenarios, allowing early termination of loops.
    data class Result(val value: Int, val isError: Boolean)
    
    fun processResults(results: List<Result>) {
        process@ for (result in results) {
            if (result.isError) {
                println("Error encountered: ${result.value}")
                break@process
            }
            // Process the result
        }
    }
    
  6. Labeled breaks in Kotlin and control flow:

    • Labeled breaks contribute to better control flow management in complex scenarios.
    loop@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                break@loop  // Breaks out of the entire loop labeled 'loop'
            }
            println("i: $i, j: $j")
        }
    }
    
  7. Nested loops and labeled breaks in Kotlin:

    • Labeled breaks are especially useful in breaking out of specific nested loops.
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                break@outer  // Breaks out of the outer loop when i=2 and j=2
            }
            println("i: $i, j: $j")
        }
    }
    
  8. Labeled breaks in functional programming with Kotlin:

    • Labeled breaks can be applied in functional programming scenarios for control flow management.
    val numbers = listOf(1, 2, 3, 4, 5)
    
    loop@ for (number in numbers) {
        if (number == 3) {
            break@loop  // Breaks out of the loop when number equals 3
        }
        println("Number: $number")
    }
    
  9. Breaking out of a specific loop with labels in Kotlin:

    • Use labeled breaks to break out of a specific loop within nested structures.
    outer@ for (i in 1..3) {
        for (j in 1..3) {
            if (i == 2 && j == 2) {
                break@outer  // Breaks out of the outer loop when i=2 and j=2
            }
            println("i: $i, j: $j")
        }
    }
    
  10. Labeling breaks for readability in Kotlin:

    • Labels improve code readability by explicitly indicating the loop or control statement being affected.
    loop@ for (i in 1..3) {
        inner@ for (j in 1..3) {
            if (i == 2 && j == 2) {
                break@loop  // Breaks out of the outer loop labeled 'loop'
            }
            println("i: $i, j: $j")
        }
    }