Ad space (banner)
Lesson 19 / 20

for comprehensions

This lesson covers the for comprehension, which expresses generating and transforming a list in one construct.

Writing for (variable <- range) yield expression builds a new list as it loops. It resembles map, but expresses transformations with complicated conditions more naturally.

The sample code writes for (i <- 1 to 10 if i % 2 == 0) yield i * i to build a new list of the squares of the even numbers from 1 to 10.

A common early stumble is forgetting yield. Without it, the for expression is just a loop that returns nothing, and no new list is built.

In professional work, for comprehensions are a readable choice whenever you are combining several lists or transforming data subject to conditions.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Scala directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)