0PricingLogin
Scala for Backend Engineering & Functional Programming · Lesson

Multiple Generators

Nested iteration.

Nested iteration made flat

A for-comprehension can have several generators. Each one is a <- line that iterates over a collection. Together they produce every combination, a kind of nested loop written flatly.

object Main {
  def main(args: Array[String]): Unit = {
    val pairs = for {
      x <- List(1, 2)
      y <- List('a', 'b')
    } yield (x, y)
    println(pairs)
  }
}

It is a cartesian product

Two generators of sizes m and n produce m × n results, the full cartesian product. The first generator is the outer loop, the second the inner loop.

object Main {
  def main(args: Array[String]): Unit = {
    val grid = for {
      row <- 1 to 3
      col <- 1 to 3
    } yield s"r$row-c$col"
    println(grid.mkString(", "))
  }
}

All lessons in this course

  1. Desugaring for
  2. Filtering with if
  3. Multiple Generators
  4. Using with Option and Future
← Back to Scala for Backend Engineering & Functional Programming