July 2018
Intermediate to advanced
400 pages
12h 14m
English
One way to exit a while loop is by changing the state it depends on.
Another way to break out of a loop is the break expression.
Consider the above example in which a while loop runs while isTavernOpen is true.
Instead of changing isTavernOpen’s value to false to end the loop, a break expression would halt the loop immediately:
var isTavernOpen = true
val isClosingTime = false
while (isTavernOpen == true) {
if (isClosingTime) {
break
}
println("Having a grand old time!")
}
Without break, "Having a grand old time!" would print one more time after the value of isClosingTime changes.
With break, the grand old times are interrupted as execution breaks out of the loop immediately.
Note that break does not stop ...
Read now
Unlock full access