The Scala 3 'for' loop (for/yield) syntax and examples

As a brief note today, here are some examples of the Scala 3 for loop syntax, including the for/do and for/yield expressions that are new to Scala 3.

Scala 3 'for' loop syntax (for/do)

// single line
for i <- ints do println(i)
for (i <- ints) println(i)

// multiline
for
    i <- ints
    if i > 2
do
    println(i)

Using 'end for' with for/do

You can also add end for to the end of a Scala 3 for loop, so the previous multiline example can also look like this:

for
    i <- ints
    if i > 2
do
    println(i)
end for

When your for loops get longer, I find that adding end for to the end of them makes them easier to read.

Scala 3 'for' loop as the body of a method

These examples show how to use a for loop as the body of a Scala method:

import io.Source

def printLines1(source: Source): Unit =
    for line <- source.getLines do println(line)

def printLines2(source: Source): Unit =
    for line <- source.getLines
    do println(line)
    
def printLines3(source: Source): Unit =
    for line <- source.getLines
    do
        println(line)
        
def printLines4(source: Source): Unit =
    for
        line <- source.getLines
    do
        println(line)
        
def printLines5(source: Source): Unit =
    for
        line <- source.getLines
        if line.trim != ""
    do
        // a multiline `do` block
        println("in `do` block of `for`")
        println(line)

Scala 3 for/yield expressions

Here are some single-line for/yield expressions:

val ints = List.range(0,9)

val tenX = for i <- ints yield i * 10
val tenX = for (i <- ints) yield i * 10
val tenX = for (i <- ints) yield (i * 10)
val tenX = for { i <- ints } yield (i * 10)

You can whichever Scala 3 for loop syntax/style you prefer.

Scala 3 for-expressions

This is the Scala 3 multiline for/yield syntax:

for i <- ints if i > 5
yield i * 10

for i <- ints if i > 5 yield
    i * 10

val tenX = for
    i <- ints
    if i > 5
yield
    i * 10

val tenX = 
    for
        i <- ints
        if i > 5
    yield
        i * 10

Notes

I use four spaces to indent for the for/yield code blocks because that tends to align well with Scala keywords like def, val, and for, but it looks like the Scala 3 standard is going to use three spaces for indentation.