Scala, lesson 5
Computers are good at doing the same thing many times. Scala gives you two main kinds of loop:
for, when you know what you're looping over, and while, when you loop until something
happens.
A range describes a sequence of whole numbers. 1 to 5 includes both ends; 1 until 5
stops before the end. A for loop takes each value in turn:
Read i <- 1 to 3 as "i takes each value from 1 to 3". The body after do is indented. A
new i is created for each pass; you can't (and don't need to) change it yourself.
Add by to change the step, including counting down:
2 exercises to try what you just read.
If the range is empty, such as 1 to 0, the body simply never runs.
You can loop over other collections too, such as the characters of a string:
for ch <- "abc" do println(ch).
A for can filter with an if guard, and it can build a new collection with yield
instead of running a body:
A while loop repeats as long as its condition is true. It checks the condition before
each pass, so it may run zero times. Usually a var changes inside the body, otherwise the
loop never ends:
Scala has no break keyword built into the language. When you need to stop a loop early, wrap
it in a boundary and call break() from inside. Both come from scala.util.boundary:
Often you can avoid this by putting the stopping rule into the while condition itself,
which is what most Scala programmers do.
A classic loop reads input until it sees a special "stop" value. Read once before the loop, then read again at the end of each pass:
Checking for null first protects you if the input ends before the marker. Because &&
short-circuits, line.trim is never called on null.
Read a whole number n (0 or more). Print the numbers from n down to 1, one per line, and
then Liftoff!.
Sample input:
Sample output:
Your fitness tracker sends one whole number per line: the steps walked each day. A line
containing 0 marks the end of the data, and anything after it must be ignored. Print how
many days came before the 0, and their total:
Sample input:
Sample output:
for i <- 1 to 3 do
println(s"Lap $i")
// Lap 1
// Lap 2
// Lap 3for i <- 0 to 10 by 5 do print(s"$i ") // 0 5 10
println()
for i <- 3 to 1 by -1 do print(s"$i ") // 3 2 1
println()for i <- 1 to 10 if i % 3 == 0 do println(i) // 3, 6, 9
val squares = for i <- 1 to 4 yield i * i // Vector(1, 4, 9, 16)var fuel = 10
while fuel > 0 do
println(s"Fuel: $fuel")
fuel -= 4
// Fuel: 10, Fuel: 6, Fuel: 2import scala.util.boundary, boundary.break
boundary:
for n <- 1 to 100 do
if n * n > 50 then break()
println(n)
// prints 1 to 7var line = readLine()
while line != null && line.trim != "end" do
println(s"Got: $line")
line = readLine()33
2
1
Liftoff!Days: <count>
Total: <sum>4000
6500
3000
0Days: 3
Total: 13500