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
10or using the preferred curly brackets style, like this:
for{i<-1to10ifi%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<-1to10ifi>3ifi<6ifi%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<-filesifpassesFilter1(file)ifpassesFilter2(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.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access