fun main() {
outer@ for (x in 0..3) {
for (y in 3 downTo 1) {
if (y == x) {
break@outer
}
println("(x,y) = ($x ,$y)")
}
}
}
Run in "play.kotlinlang.org", the result is
(x,y) = (0 ,3)
(x,y) = (0 ,2)
(x,y) = (0 ,1)
(x,y) = (1 ,3)
(x,y) = (1 ,2)
I think you misunderstood what break
does. It stops the loop, not goes to the next element. You should either use continue@outer
or simply break
(to break the inner loop).
1 Like
I think so too. He probably wanted to use either continue
or put that printing line under a condition x != y
if loop was not to be skipped entirely.
Yes, it does. It works the same as in pretty much any other language - it terminates the whole loop, not only the current iteration. To jump to the next iteration, we use continue
if the language supports it.
1 Like