3.3. Using a for Loop with Embedded if Statements (Guards)

Problem

You want to add one or more conditional clauses to a for loop, typically to filter out some elements in a collection while working on the others.

Solution

Add an if statement after your generator, like this:

// print all even numbers
scala> for (i <- 1 to 10 if i % 2 == 0) println(i)
2
4
6
8
10

or using the preferred curly brackets style, like this:

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

These if statements are referred to as filters, filter expressions, or guards, and you can use as many guards as are needed for the problem at hand. This loop shows a hard way to print the number 4:

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

Discussion

Using guards with for loops can make for concise and readable code, but you can also use the traditional approach:

for (file <- files) {
  if (hasSoundFileExtension(file) && !soundFileIsLong(file)) {
    soundFiles += file
  }
}

However, once you become comfortable with Scala’s for loop syntax, I think you’ll find it makes the code more readable, because it separates the looping and filtering concerns from the business logic:

for {
  file <- files
  if passesFilter1(file)
  if passesFilter2(file)
} doSomething(file)

As a final note, because guards are generally intended to filter collections, you may want to use one of the many filtering methods that are available to collections (filter, take, drop, etc.) instead of a for loop, depending on your needs.

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.