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: