This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 3.3, “How to use 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: