Since Scala does not have old Java style for
loops with index,
// does not work
val xs = Array("first", "second", "third")
for (i=0; i<xs.length; i++) {
println("String #" + i + " is " + xs(i))
}
How can we iterate efficiently, and without using var
's?
You could do this
val xs = Array("first", "second", "third")
val indexed = xs zipWithIndex
for (x <- indexed) println("String #" + x._2 + " is " + x._1)
but the list is traversed twice – not very efficient.
Best Answer
Much worse than traversing twice, it creates an intermediary array of pairs. You can use
view
. When you docollection.view
, you can think of subsequent calls as acting lazily, during the iteration. If you want to get back a proper fully realized collection, you callforce
at the end. Here that would be useless and costly. So change your code to