Kotlin Tutoial
Basics
Control Flow
Array & String
Functions
Collections
OOPs Concept
Exception Handling
Null Safety
Regex & Ranges
Java Interoperability
Miscellaneous
Android
In Kotlin, the break
statement is used to terminate the nearest enclosing loop, be it a for
loop or a while
loop. This is known as an "unlabeled break" because it doesn't refer to any specific label to determine which loop to exit from.
Let's explore how to use an unlabeled break
in Kotlin with some examples.
break
in a Simple LoopImagine we're searching through an array of numbers, and we want to stop the search as soon as we find the number 5.
val numbers = arrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) for (num in numbers) { if (num == 5) { println("Found the number 5!") break } println("Checking number $num") }
Here, when the number 5 is found, the break
statement will terminate the for
loop, and no numbers after 5 will be checked.
break
in Nested LoopsIn the case of nested loops, an unlabeled break
will only terminate the innermost loop. Let's consider a 2D grid (represented by nested arrays), and we're looking for the value 5. Once we find it, we want to exit the inner loop:
val matrix = arrayOf( arrayOf(1, 2, 3), arrayOf(4, 5, 6), arrayOf(7, 8, 9) ) for (row in matrix) { for (num in row) { if (num == 5) { println("Found the number 5!") break // This will break out of the inner loop only } println("Checking number $num") } }
In this example, after finding the number 5, the inner loop will be terminated, but the outer loop will continue to the next row.
break
An unlabeled break
can only break out of the nearest enclosing loop. If you want to break out of outer loops or specify which loop to exit in more complex control structures, you would need to use a labeled break
.
The unlabeled break
statement in Kotlin provides a straightforward way to exit from the closest loop. For more complex control flow where you might want to exit from outer loops or specific loops, Kotlin offers labeled breaks. The explicit nature of breaks in Kotlin helps in writing more readable and maintainable code.
How to break out of a loop in Kotlin:
break
statement is used to terminate a loop prematurely.for (i in 1..10) { if (i == 5) { break } println(i) }
Kotlin loop control flow:
for (i in 1..5) { println(i) }
Using break in Kotlin for loop:
break
statement to exit a for
loop.for (i in 1..10) { if (i > 5) { break } println(i) }
Kotlin continue statement:
continue
statement skips the rest of the loop's code and moves to the next iteration.for (i in 1..5) { if (i == 3) { continue } println(i) }
Loop termination in Kotlin:
var i = 1 while (i <= 5) { println(i) i++ }
Breaking out of nested loops in Kotlin:
break
statement to exit nested loops.outer@ for (i in 1..3) { for (j in 1..3) { if (i * j > 4) { break@outer } println("$i * $j = ${i * j}") } }