Break statements

Kotlin provides break statements, which are used to break the continuation of a loop. Break statements immediately terminate the iteration of a loop when the test condition is met. This is often used in while, do whileand for loops in order to end the current loop and exit where conditions may need to be defined inside the loop for specific reasons:

fun main(args: Array<String>) {
for (i in 1..10) {
println("For $i")
if(i >= 5) {
break;
}
}
}

Notice that the break statement terminates the program execution where it is placed. If the break statement is in an inner loop, the outer loop will perform its task normally. This is because only the inner loop will end and the outer loop will continue its iterations as defined until it fulfills its condition. Take an example of a nested loop and print the value of i and j but break the inner loop when both values are same:

for (i in 1..3) {
for (j in 1..3) {
println("$i , $j")
if(i==j) {
break;
}
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.189.186