August 2013
Intermediate to advanced
720 pages
16h 23m
English
You want to loop over the elements in a collection using a
for loop, possibly creating a new
collection from the existing collection using the
for/yield combination.
You can loop over any Traversable type (basically any sequence)
using a for loop:
scala>val fruits = Traversable("apple", "banana", "orange")fruits: Traversable[String] = List(apple, banana, orange) scala>for (f <- fruits) println(f)apple banana orange scala>for (f <- fruits) println(f.toUpperCase)APPLE BANANA ORANGE
If your algorithm is long, perform the work in a block following a
for loop:
scala>val fruits = Array("apple", "banana", "orange")fruits: Array[String] = Array(apple, banana, orange) scala>for (f <- fruits) {| // imagine this required multiple lines |val s = f.toUpperCase|println(s)|}APPLE BANANA ORANGE
This example shows one approach to using a counter inside a
for loop:
scala> for (i <- 0 until fruits.size) println(s"element $i is ${fruits(i)}")
element 0 is apple
element 1 is banana
element 2 is orangeYou can also use the zipWithIndex method when you need a loop
counter:
scala>for ((elem, count) <- fruits.zipWithIndex) {|println(s"element $count is $elem")|}element 0 is apple element 1 is banana element 2 is orange
When using zipWithIndex,
consider calling view before
zipWithIndex:
// added a call to 'view'
for ((elem, count) <- fruits.view.zipWithIndex) {
println(s"element $count is $elem")
}See the next recipe for details. ...
Read now
Unlock full access