Scala Control Flow

Conditionals and loops in Scala

If Expression

val max = if (a > b) a else b # if as expression
val result = if (x > 0) {
    "positive"
} else if (x < 0) {
    "negative"
} else {
    "zero"
}

For Loop

for (i <- 1 to 5) { # loop 1 to 5 (inclusive)
    println(i)
}
for (i <- 1 until 5) { } # 1 to 4 (exclusive)

For Comprehension

val result = for { # for comprehension
    i <- 1 to 3
    j <- 1 to 2
} yield i * j # generates collection

While Loop

while (condition) { # repeat while true
    // code
}
do { # execute at least once
    // code
} while (condition)

Loop Control

// No break/continue in Scala
// Use return, recursion, or filters instead