Sometimes, you need to alter the flow of a loop by either exiting it completely or skipping the current iteration. Kotlin provides the break and continue keywords for this.
The break statement is used to jump out of a loop entirely.
fun main() {
var i = 0
while (i < 10) {
println(i)
i++
if (i == 4) {
break // Stops the loop when i is 4
}
}
}
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues with the next iteration in the loop.
for (i in 0..5) {
if (i == 3) continue // Skips printing the number 3
println(i)
}