yield in for
In this page:
yield in for
Adding yield to a for comprehension, for (x <- collection) yield transform(x), transforms each element and collects the results into a new collection of the same type as the source, instead of just running side effects. This is functionally equivalent to calling .map (and with filters/multiple generators, roughly equivalent to .flatMap/.filter), but often reads more clearly for complex, multi-generator logic. The resulting collection's type matches the type being iterated over.
Note: for (x <- xs) yield f(x) is syntactic sugar that the compiler translates into a chain of map/flatMap/filter calls.
Example: yield in for
object Main extends App {
val numbers = 1 to 5
val squares = for (n <- numbers) yield n * n
println(squares)
val evens = for (n <- numbers if n % 2 == 0) yield n
println(evens)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: