Scala Language Basic For Comprehension


Example

This demonstrates a filter on a for-loop, and the use of yield to create a 'sequence comprehension':

for ( x <- 1 to 10 if x % 2 == 0)
  yield x

The output for this is:

scala.collection.immutable.IndexedSeq[Int] = Vector(2, 4, 6, 8, 10)

A for comprehension is useful when you need to create a new collection based on the iteration and it's filters.