O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The for Expression

The foreach method provides internal iterators on collections—you don’t control the looping. You simply provide code to execute in the context of each iteration. However, if you’d like to control the looping or work with multiple collections at the same time, you can use an external iterator, the for expression. Let’s look at a simple loop:

UsingCollections/PowerOfFor.scala
 
for​ (i <- 1 to 3) { print(​"ho "​) }

The code prints “ho ho ho.” It’s a short form of the general syntax of the following expression:

 
for([pattern <- generator; definition*]+; filter*)
 
[yield] expression

The for expression takes as a parameter one or more generators, with zero or more definitions and zero or more filters. These are separated from ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required