Scala also has a while
loop, but because Scala puts an emphasis on functional programming — and because the collections classes have dozens of built-in methods — I rarely use it. But if you need it, this is what it looks like:
var i = 0
while i < 3 do
println(i)
i += 1
If you prefer, you can add end while
to the end of the loop:
while i < 3 do
println(i)
i += 1
end while
The while
loop is generally used for a side-effect, such as printing to the console with println
or updating a mutable variable, and when you write code in an FP style you avoid side effects as much as possible, so you don’t use while
loops. Frankly, I have written maybe one while
loop every year or two, so I don’t want to put too much emphasis on it here.
Exercises
The exercises for this lesson are available here.
More information
For more information about how FP avoids side effects, see my book, Functional Programming, Simplified.