In this tutorial you will learn about the Kotlin break and its application with practical example.
Kotlin break statement
In Kotlin, break statement inside any loop gives you way to break or terminate the execution of loop containing it, and transfers the execution to the next statement following the loop. It is almost always used with if..else construct.
Syntax:-
1 2 3 4 5 |
for (...) { if (condition) { break } } |
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main(args: Array<String>) { var count = 0 while (count <= 10) { count++ if (count == 5) { break } println("Inside loop $count") } print("Out of while loop") } |
In this above program, the variable count is initialized as 0. Then a while loop is executed as long as the variable count is less than 10.
Inside the while loop, the count variable is incremented by 1 with each iteration (count = count + 1).
Next, we have an if statement that checks the variable count is equal to 5, if it return TRUE causes loop to break or terminate.
Within the loop there is a println() statement that will execute with each iteration of the while loop until the loop breaks.
Then, there is a final println() statement outside of the while loop.
When we run this code, our output will be as follows –
Output:-
1 2 3 4 5 |
Inside loop 1 Inside loop 2 Inside loop 3 Inside loop 4 Out of while loop |
Kotlin Labeled break
The standard unlabeled break statement is used to terminates the nearest enclosing loop. In Kotlin, there is another form of break (labeled break) statement is used to terminate specified loop (can be outer loop). In Kotlin, Label is an identifier which is followed by @ sign, for example abc@, test@.
Example:-
1 2 3 4 5 6 7 8 9 |
fun main(args: Array<String>) { outer@ for (i in 1..5) { for (j in 1..3) { println("i = $i and j = $j") if (i == 2) break@outer } } } |
Output:-
1 2 3 4 |
i = 1 and j = 1 i = 1 and j = 2 i = 1 and j = 3 i = 2 and j = 1 |
Here, when i == 2 expression is evaluated to true, break@outer is executed which terminates the loop marked with label outer@.