Kotlin break and continue Explained (2025 Guide to Mastering Loop Control)
Loops are the heartbeat of repetitive tasks, but sometimes you need to steer their flow with precision—enter break and continue! π These statements give you fine-grained control, letting you exit loops early or skip iterations. Whether you’re filtering data, searching collections, or handling nested loops, this 2025 guide dives deep into every aspect of break and continue, packed with pro-level tips and real-world examples to make your code shine! π
Break: Exit the Loop Early π
The break statement halts a loop immediately when a condition is met, jumping to the code after the loop. It’s perfect for early termination when you’ve found what you need! π―
Provided Example: Stop at 4 in a while loop:
fun main() {
var i = 0 // π’ Initialize counter
while (i < 10) { // π Loop until 10
println(i) // π Print current value
i++ // ➕ Increment
if (i == 4) { // π Check for exit condition
break // π Exit loop
}
} // Outputs: 0, 1, 2, 3 π
}
Example: Break in a For Loop
fun main() {
for (i in 1..10) { // π Iterate from 1 to 10
if (i == 6) break // π Stop at 6
println("Number: $i") // π Print number
} // Outputs: Number: 1, Number: 2, Number: 3, Number: 4, Number: 5 π
}
Break Basics:
- π Full Stop: Exits the nearest enclosing loop entirely. πͺ
- π Conditional Exit: Triggers on a specific condition (e.g., i == 4). ⚖️
- ⚡ Efficient: Saves cycles by skipping unnecessary iterations. π♂️
- ✅ Use Case: Ideal for searches or when a goal is met. π―
Break Tip: Use break to optimize loops when further iterations are redundant. π ️
Continue: Skip to the Next Iteration ⏭️
The continue statement skips the rest of the current loop iteration and jumps to the next one, keeping the loop running. It’s great for filtering out unwanted cases! π
Provided Example: Skip 4 in a while loop:
fun main() {
var i = 0 // π’ Initialize counter
while (i < 10) { // π Loop until 10
if (i == 4) { // π Check for skip condition
i++ // ➕ Increment before continue
continue // ⏭️ Skip to next iteration
}
println(i) // π Print number
i++ // ➕ Increment
} // Outputs: 0, 1, 2, 3, 5, 6, 7, 8, 9 π
}
Example: Continue in a For Loop
fun main() {
for (i in 1..5) { // π Iterate from 1 to 5
if (i % 2 == 0) continue // ⏭️ Skip even numbers
println("Odd: $i") // π Print odd numbers
} // Outputs: Odd: 1, Odd: 3, Odd: 5 π
}
Continue Highlights:
- ⏭️ Skip Current: Bypasses remaining code in the current iteration. π
- π Conditional Skip: Triggers on a specific condition (e.g., i == 4). ⚖️
- ⚡ Keeps Going: Continues the loop without interruption. π♂️
- ✅ Use Case: Perfect for filtering or skipping invalid data. π
Continue Tip: Ensure the loop variable is updated before continue in while or do..while to avoid infinite loops. π«
Labeled Break: Precision Exit π―
In nested loops, a plain break exits only the innermost loop. A labeled break lets you exit an outer loop by referencing a label (e.g., outerLoop@), offering precise control. π§©
Provided Example: Break out of nested loops:
fun main() {
outerLoop@ for (i in 1..3) { // π·️ Label outer loop
for (j in 1..3) { // π Inner loop
println("i = $i, j = $j") // π Print coordinates
if (i == 2 && j == 2) break@outerLoop // π Exit outer loop
}
} // Outputs: i = 1, j = 1
// i = 1, j = 2
// i = 1, j = 3
// i = 2, j = 1
// i = 2, j = 2 π
}
Example: Labeled Break in While Loop
fun main() {
var i = 1 // π’ Outer counter
outer@ while (i <= 3) { // π·️ Label outer loop
var j = 1 // π’ Inner counter
while (j <= 3) { // π Inner loop
println("i = $i, j = $j") // π Print
if (i == 2 && j == 1) break@outer // π Exit outer loop
j++ // ➕ Increment inner
}
i++ // ➕ Increment outer
} // Outputs: i = 1, j = 1
// i = 1, j = 2
// i = 1, j = 3
// i = 2, j = 1 π
}
Labeled Break Power:
- π― Targeted Exit: Breaks a specific loop using a label. π·️
- π Multi-Level Control: Exits nested loops at once. πͺ
- π Use Case: Essential for matrix processing or complex iterations. π§©
- ⚡ Clear Intent: Labels make exit points explicit. π§
Labeled Break Tip: Use descriptive labels (e.g., matrixLoop@) for clarity in complex code. π
Labeled Continue: Selective Skip π
A labeled continue skips to the next iteration of a labeled outer loop, bypassing the inner loop’s remaining code. It’s ideal for selective iteration control. ⏭️
Provided Example: Skip when j == 2 in nested loops:
fun main() {
outerLoop@ for (i in 1..3) { // π·️ Label outer loop
for (j in 1..3) { // π Inner loop
if (j == 2) continue@outerLoop // ⏭️ Skip to next outer iteration
println("i = $i, j = $j") // π Print coordinates
}
} // Outputs: i = 1, j = 1
// i = 2, j = 1
// i = 3, j = 1 π
}
Example: Labeled Continue in While Loop
fun main() {
var i = 1
outer@ while (i <= 3) {
var j = 1
while (j <= 3) {
if (j == 2) {
j++
i++ // ✅ ensure outer counter increments before skipping
continue@outer
}
println("i = $i, j = $j")
j++
}
i++
}
}
Labeled Continue Benefits:
- π Targeted Skip: Jumps to the next iteration of a labeled loop. π·️
- ⏭️ Multi-Level Skip: Bypasses inner loop code to continue outer loop. π
- π Use Case: Useful for filtering in nested iterations. π
- ⚡ Explicit Control: Labels clarify which loop is affected. π§
Labeled Continue Tip: Avoid overusing labels to keep code readable; refactor complex logic into functions if needed. π§Ή
Break and Continue in do..while Loops π
break and continue work seamlessly in do..while loops, offering control over iterations that run at least once. π
Example: Break and Continue in do..while
fun main() {
var i = 0 // π’ Initialize counter
do { // π Run at least once
if (i == 3) break // π Exit at 3
if (i % 2 == 0) { // π Skip even numbers
i++ // ➕ Increment before continue
continue // ⏭️ Skip to next iteration
}
println("Odd: $i") // π Print odd numbers
i++ // ➕ Increment
} while (i < 5) // π Condition
// Outputs: Odd: 1 π
}
do..while Control Benefits:
- π Guaranteed Run: Ensures at least one iteration, even with break. ✅
- π Break: Stops the loop early, as in other loops. πͺ
- ⏭️ Continue: Skips to the next iteration, checking the condition. π
- ✅ Use Case: Retry logic or user prompts where one run is required. π§©
do..while Tip: Use do..while with break or continue for controlled retries or input validation. π ️
Functional Alternatives to Break and Continue ⚡
Kotlin’s functional programming offers alternatives to break and continue using collection operations like takeWhile, filter, or forEach, providing a declarative approach. π§
Example: Functional Equivalent to Break
fun main() {
(1..10).takeWhile { it < 6 } // π Stop at 6 (like break)
.forEach { println("Number: $it") } // π Print numbers
// Outputs: Number: 1, Number: 2, Number: 3, Number: 4, Number: 5 π
}
Example: Functional Equivalent to Continue
fun main() {
(1..5).filter { it % 2 != 0 } // π Skip even numbers (like continue)
.forEach { println("Odd: $it") } // π Print odd numbers
// Outputs: Odd: 1, Odd: 3, Odd: 5 π
}
Functional Benefits:
- ⚡ Declarative: Focuses on what to achieve, not how to loop. π§
- π§Ή Clean Syntax: Eliminates explicit loop control statements. π
- π Pipeline-Friendly: Combines with map, filter, etc. π
- ✅ Use Case: Ideal for functional pipelines or immutable data. π
Functional Tip: Use functional alternatives for simple filtering or early termination; reserve break and continue for complex control flows. π
Practical Use Case: Search Algorithm π
Use break to implement a linear search, exiting once the target is found. π ️
fun main() {
val numbers = listOf(3, 7, 2, 9, 4) // π’ Number list
val target = 9 // π Search target
var index = -1 // π Result index
for (i in numbers.indices) { // π Iterate with indices
if (numbers[i] == target) { // π Found target
index = i // ✅ Store index
break // π Exit loop
}
}
println(if (index != -1) "Found $target at index $index" else "$target not found")
// Outputs: Found 9 at index 3 π
}
Search Tip: Use break to optimize searches by stopping as soon as the target is found. π―
Practical Use Case: Data Filtering with Continue π
Use continue to filter invalid data during processing, skipping unwanted iterations. π
fun main() {
val data = listOf("Apple", "", "Banana", " ", "Cherry") // π Data list
val validItems = mutableListOf<String>() // π¦ Store valid items
for (item in data) { // π Iterate over data
if (item.isBlank()) continue // ⏭️ Skip blank or empty strings
validItems.add(item) // ✅ Add valid item
}
println("Valid items: $validItems") // Outputs: Valid items: [Apple, Banana, Cherry] π
}
Filtering Tip: Use continue to streamline data processing by skipping invalid entries without exiting the loop. π§Ή
Edge Cases and Error Handling π«
Handle edge cases like empty collections or invalid conditions to ensure robust loop control.
Example: Empty Collection
fun main() {
val items = emptyList<Int>() // π’ Empty list
for (item in items) { // π Iterate (no iterations)
if (item == 5) break // π Would break, but loop is empty
println(item) // π Would print
}
println("No items processed") // Outputs: No items processed π
}
Example: Infinite Loop Prevention
fun main() {
var i = 0 // π’ Counter
while (i < 5) { // π Loop
if (i == 3) { // π Condition
i++ // ➕ Must increment before continue
continue // ⏭️ Skip
}
println(i) // π Print
i++ // ➕ Increment
} // Outputs: 0, 1, 2, 4 π
}
Error Handling Tip: Always check for empty inputs and ensure loop variables are updated to prevent infinite loops. π‘️
Performance Considerations ⚙️
break and continue are lightweight, but optimize their use for performance:
- ⚡ Early Exit: Use break to avoid unnecessary iterations in large loops. π♂️
- π§Ή Minimize Conditions: Simplify conditions for break or continue to reduce checks. π
- π Functional Alternatives: Consider takeWhile or filter for large datasets to leverage Kotlin’s optimizations. π§
- π« Avoid Overuse: Excessive break or continue can make code harder to follow. π§Ή
Performance Tip: Profile loops with break and continue in performance-critical sections to ensure efficiency. π
Best Practices for Break and Continue ✅
- π§Ή Use Sparingly: Limit break and continue to keep loop logic clear and maintainable. π
- ✅ Clear Conditions: Use simple, readable conditions for triggering break or continue. π
- π·️ Descriptive Labels: Name labels clearly (e.g., searchLoop@) in nested loops. π
- π‘️ Avoid Infinite Loops: Ensure loop variables are updated before continue in while or do..while. π«
- ⚡ Functional Alternatives: Consider takeWhile or filter for declarative code when appropriate. π§
- π Document Intent: Add comments to explain why break or continue is used, especially with labels. π§π»
Frequently Asked Questions (FAQ) ❓
- When should I use break vs. continue? π€
Use break to exit a loop entirely (e.g., found a target); use continue to skip an iteration and keep looping (e.g., filter invalid data). π⏭️ - Why use labeled breaks/continues? π·️
Labeled break and continue target specific loops in nested structures, providing precise control. π― - Can break and continue be used in all loops? π
Yes, they work in for, while, and do..while loops, with or without labels. ✅ - Are there functional alternatives to break and continue? ⚡
Yes, use takeWhile for break-like behavior and filter for continue-like filtering in functional code. π§ - How do I avoid infinite loops with continue? π«
Update loop variables before continue in while or do..while to ensure progress. π ️ - Do break and continue affect performance? π
They’re lightweight, but optimize conditions and minimize usage to maintain readability and efficiency. ⚙️
Comments
Post a Comment