MOCKSTACKS
EN

# Scala For Expressions

## Examples

#### Basic For Loop

``````for (x <- 1 to 10)
println("Iteration number " + x)``````

This demonstrates iterating a variable, x, from 1 to 10 and doing something with that value. The return type of this for comprehension is Unit.

#### Basic For Comprehension

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.

#### Nested For Loop

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))``````

## Conclusion

In this page (written and validated by ) you learned about Scala For Expressions . What's Next? If you are interested in completing Scala tutorial, your next topic will be learning about: Scala Functions.

Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.