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

Here are some examples of the Scala 3 for loop syntax, including for/do and for/yield expressions.

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)

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.

... this post is sponsored by my books ...