yield in for
Adding yield to a for loop makes it collect the results into a new list, like a machine that turns each toy into a painted toy and stacks them. Instead of just repeating, it produces something.
In this page:
Syntax
val result = for (item <- collection) yield expression
val filtered = for (item <- collection if condition) yield expression
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
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
forwithoutyieldand expecting a new collection, when it returnsUnitand just runs the body. - Putting side effects like
printlnin theyieldexpression, whenyieldis meant for producing a value. - Using
yieldon aRangeand being surprised the result is aVectorrather than aList, since the result type follows the source collection.
Chapter Summary
if/else,while,do-while, andforloops control program flow.forcomprehensions andyieldbuild results from loops.- Breaking out of a loop uses
scala.util.control.Breaks.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: