Scala Language Nested For Loop


Example

This shows how you can iterate over multiple variables:

for {
  x <- 1 to 2
  y <- 'a' to 'd'
} println("(" + x + "," + y + ")")

(Note that to here is an infix operator method that returns an inclusive range. See the definition here.)

This creates the output:

(1,a)
(1,b)
(1,c)
(1,d)
(2,a)
(2,b)
(2,c)
(2,d)

Note that this is an equivalent expression, using parentheses instead of brackets:

for (
  x <- 1 to 2
  y <- 'a' to 'd'
) println("(" + x + "," + y + ")")

In order to get all of the combinations into a single vector, we can yield the result and set it to a val:

val a = for {
  x <- 1 to 2
  y <- 'a' to 'd'
} yield "(%s,%s)".format(x, y)
// a: scala.collection.immutable.IndexedSeq[String] = Vector((1,a), (1,b), (1,c), (1,d), (2,a), (2,b), (2,c), (2,d))