
#Scala for loop series
These statements can be demonstrated with a series of examples. A for loop with a yield expression and a guard is translated to a withFilter method call on the collection, followed by a map method call.Īgain, the Specification is more detailed than this, but those statements will help get you started in the right direction.A for loop with a yield expression is translated to a map method call on the collection.

#Scala for loop how to
Recipe 3.3 demonstrates how to use guards ( if statements in for loops), but here’s a quick preview: The next recipe demonstrates how to use this technique to create multiple loop counters. Using a Range like this is known as using a generator. Scala> for (e for (e val newArray = for (e val newArray = for (e for ((e, count) for (i 1 to 3 I prefer to iterate over the array with the following for loop syntax, because it’s clean and easy to remember: Val a = Array("apple", "banana", "orange") This solution focuses primarily on the for loop and foreach method. There are many ways to loop over Scala collections, including for loops, while loops, and collection methods like foreach, map, flatMap, and more.

You want to iterate over the elements in a Scala collection, either to operate on each element in the collection, or to create a new collection from the existing collection. This is Recipe 3.1, “How to loop over a collection with for and foreach (and how a for loop is translated).” Problem This is an excerpt from the Scala Cookbook (partially modified for the internet).
