Control Structures

(There's no do-while in Scala 3; use while { body; cond } do ().)

7.1 if / else

// Scala 3 syntax
if x > 0 then println("positive")
else if x < 0 then println("negative")
else println("zero")

// Scala 2 syntax (also valid in Scala 3)
if (x > 0) println("positive") else println("non-positive")

7.2 match (preview — see §15)

val day = 3
val name = day match
  case 1 => "Mon"
  case 2 => "Tue"
  case 3 => "Wed"
  case _ => "Other"

7.3 while loops

(There's no do-while in Scala 3; use while { body; cond } do ().)

var i = 0
while i < 5 do
  println(i)
  i += 1

7.4 for loops

for i <- 1 to 5 do println(i)               // 1..5 inclusive
for i <- 1 until 5 do println(i)            // 1..4
for i <- 10 to 1 by -2 do println(i)        // 10, 8, 6, 4, 2
for
  i <- 1 to 3
  j <- 1 to 3
  if i != j
do println(s"$i,$j")

for (name, idx) <- List("a", "b").zipWithIndex do println(s"$idx: $name")

7.5 for-yield (comprehension producing a value)

val squares = for i <- 1 to 5 yield i * i          // Vector(1, 4, 9, 16, 25)
val evens = for i <- 1 to 10 if i % 2 == 0 yield i

7.6 Breaking out of loops

No break keyword; use scala.util.boundary:

Prefer collection methods (find, takeWhile, exists).

import scala.util.boundary, boundary.break

val firstNeg = boundary:
  for x <- List(3, 1, -4, 5) do
    if x < 0 then break(Some(x))
  None