Scala for loop syntax examples (including yield and guards)

Scala FAQ: Can you share some examples of the Scala for loop syntax?

Sure. There are several ways you can write a Scala for loop, and I’ll try to show a short example of each of those. I’m going to start with a comparison to Java for loops, because that's what I was just thinking about.

Back to top

Java for loop with counter

In Java you might write a for loop with a counter like this:

for (int i = 0; i < 10; i++) {
  System.out.println(i);
}

The equivalent for loop in Scala looks like this:

for (i <- 1 to 10) {
  println(i)
}

(The use of parentheses isn’t necessary in either example, but most for loops will be longer.)

Back to top

Java 5 for loop vs Scala for loop

Beginning with Java 5 you can write a Java for loop like this:

List list = getList();
for (String s : list) {
  // treat s as a String here; no casting needed
  System.out.println(s);
}

The equivalent Scala for loop looks like this:

for (s <- getList) {
  println(s)
}
Back to top

Scala for loop with yield

With Scala you can also write a Scala for loop with a yield statement, as shown in these examples:

scala> for (i <- 1 to 5) yield i
res0: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 2, 3, 4, 5)

scala> for (i <- 1 to 5) yield i * 2
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

scala> for (i <- 1 to 5) yield i % 2
res2: scala.collection.immutable.IndexedSeq[Int] = Vector(1, 0, 1, 0, 1)
Back to top

Scala for loop with guards

You can also create Scala for loops with embedded if statements, or guards. A for loop with a guard looks like this:

for {
  i <- 0 to 10
  if i % 2 == 0
} println(i)

This prints:

0
2
4
6
8
10

Notice that I used the { and } characters around the body of the for loop in this example. It’s much more common to use these brackets when the body contains multiple lines of code, as in this example.

A for loop with multiple guards looks like this:

for { 
  i <- 0 to 10
  if i % 2 == 0
  if i > 5
} println(i)

This prints:

6
8
10
Back to top

Scala for loop syntax examples

I hope these Scala for loop syntax examples have been helpful.

Back to top