Loops and for comprehensions

Scala has a while loop for the case that needs one and a for comprehension for everything else. A for over a collection with yield builds a new collection and has the type of the original, so a loop that transforms data is an expression with a value.

for and yield

The generator <- takes each element, a guard if keeps some of them, and yield gives the value of each one. A for without yield runs for its effect and returns Unit:

loops.scala

@main def loops(): Unit = for i <- 1 to 3 do println(i) val squares = for n <- 1 to 5 yield n * n println(squares) val even = for n <- 1 to 10 if n % 2 == 0 yield n println(even) for x <- 1 to 2 y <- 1 to 2 do println(s"$x,$y") var count = 3 while count > 0 do println(s"countdown $count") count -= 1 List("a", "b").foreach(println) val pairs = (1 to 3).zip(List("a", "b", "c")) println(pairs)

scala-cli run --server=false loops.scala

1
2
3
Vector(1, 4, 9, 16, 25)
Vector(2, 4, 6, 8, 10)
1,1
1,2
2,1
2,2
countdown 3
countdown 2
countdown 1
a
b
Vector((1,a), (2,b), (3,c))

squares is a IndexedSeq[Int] and prints as Vector(...); the type of the result follows the type of the generator, so a for over a List yields a List. The underscore form map(_ * 2) in a later lesson is the same function as map(n => n * 2).

Several generators

Several <- lines in one for are nested loops, and the later ones can use the earlier value: a flat for over two generators is the flatMap of the collections lesson. The braces form for { x <- ...; y <- ... } is still accepted and does the same thing.

while and foreach

A while loop needs a var and returns Unit, so the course uses it only where the number of iterations is not known in advance. foreach is the other way to run a function for its effect on every element, and List("a", "b").foreach(println) passes the method println itself, not a lambda that calls it.

Leaving a loop early

Scala has no break statement, because a loop that returns a value has no need of one: find stops at the first match. When the search is more complex than a predicate, scala.util.boundary gives the early exit a name and a type. The block returns the argument of break, or its last expression when it never breaks:

boundary.scala

import scala.util.boundary import scala.util.boundary.break @main def firstOver(limit: Int): Unit = val numbers = List(1, 4, 9, 16) val found = boundary: for n <- numbers do if n > limit then break(n) -1 println(found) println(numbers.find(_ > limit).getOrElse(-1))

scala-cli run --server=false boundary.scala -- 10

16
16

Both lines print 16: the boundary leaves the loop with the first element over the limit, and find plus getOrElse does the same for a predicate. The second form is the one to reach for; the first is for a body that cannot be written as one predicate, and a break outside its boundary is a compile error.

Related

Article author: Arthur Isaev