while Loops
Prerequisites: for loops and ranges
while repeats as long as a condition is true:
@main def doubling(): Unit =
var balance = 100.0
var months = 0
while balance < 200 do
balance *= 1.1
months += 1
println(s"Doubled after $months months")
Doubled after 8 months
while needs a var that changes — otherwise the loop never ends. That's
why idiomatic Scala uses it less than other languages do: collection
methods, for, and recursion usually express the same thing without
mutable state.
No break or continue
Scala has no break or continue keywords. Instead:
@main def noBreak(): Unit =
val numbers = List(3, 8, 12, 5, 20)
val firstBig = numbers.find(_ > 10)
println(firstBig)
val beforeBig = numbers.takeWhile(_ <= 10)
println(beforeBig)
for n <- numbers if n % 2 == 0 do println(n)
Some(12)
List(3, 8)
8
12
20
findstops at the first match — the usual reason forbreak.takeWhiletakes elements until the condition fails.- A
forfilter (if) replacescontinue.
(scala.util.boundary exists for the rare case where you really need to
exit early from deep inside a loop.)