Learn/Scala/5. Loops
Lesson 5 of 8
Sign in

Scala, lesson 5

Loops

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.

for loops and ranges

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.

Exercise 1

Countdown

Press Ctrl Enter or Check to test your code.

Exercise 2

Step counter

Press Ctrl Enter or Check to test your code.

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).

Guards and yield

A for can filter with an if guard, and it can build a new collection with yield instead of running a body:

while loops

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:

Leaving early

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.

Reading until a marker

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.

Further reading

  • Scala 3 Book: Control Structures (for, while)
  • Scala API: scala.util.boundary
  • Scala API: Range

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 3
for 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: 2
import scala.util.boundary, boundary.break

boundary:
  for n <- 1 to 100 do
    if n * n > 50 then break()
    println(n)
// prints 1 to 7
var line = readLine()
while line != null && line.trim != "end" do
  println(s"Got: $line")
  line = readLine()
3
3
2
1
Liftoff!
Days: <count>
Total: <sum>
4000
6500
3000
0
Days: 3
Total: 13500