The break statement with labeled for loop 

Break statements always break the nearest or parent loop where the break is placed, as we saw in previous example. But what if we want to stop the loop iterations altogether whenever a certain condition is met in a nested inner loop? To address such conditions, Kotlin provides a concept called a labeled for loop. This means that an alias name is assigned to a for loop to break it by using the break@nameOfTheLoop statement. Assign a name to the for loop, as described here, and call the loop by using the break statement. When the variables i and j are equal to 2, by using break@outLoop, the break statement would know which for loop to terminate:

fun main(args: Array<String>) {

println("Labled For Loop")
outLoop@ for (i in 1..3) {
for (j in 1..3) {
if(i==2 && j==2) {
break@outLoop
}
println("$i , $j")
}
}
}

So, the outer for loop would run once and the inner for loop would execute its body three times. On the second iteration of the outer loop, when both i and j would equal 2, the break statement would call the outer loop to terminate. So, if the outer loop terminates, this means that the inner loop terminates automatically.

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

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