engineeringsoli.blogg.se

Scala for loop
Scala for loop







  1. #Scala for loop how to
  2. #Scala for loop series

#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

  • A for loop with a guard (see Recipe 3.3) is translated to a sequence of a withFilter method call on the collection followed by a foreach call.
  • A simple for loop that iterates over a collection is translated to a foreach method call on the collection.
  • I encourage you to read the Specification for details on the rules, but a simplification of those rules can be stated as follows: The Scala Language Specification provides details on precisely how a for loop is translated under various conditions. Scala> a.foreach(e => println(e.toUpperCase))Īs before, if your algorithm requires multiple lines, perform your work in a block:Īs you work with Scala, it’s helpful to understand how for loops are translated by the compiler. When you have an algorithm you want to run on each element in the collection, just use the anonymous function syntax: Scala> for (i "Robert", "lname" -> "Goren")

    #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.

    scala for loop

    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).

  • show more info on classes/objects in repl.








  • Scala for loop