Scala for loop

0 comments

In my previous post I've explained how to use while and do-while loops. In today's post I will show you how to use a for loop. For loop allows you to do quite a lot. It was designed to iterate through a collection, do range iterations, producing a new collection, perform nested iterations easily, filter and mid-stream variable bindings. I will skip mid-stream variable binding and producing new collections since these are advanced topics. I will explain them in the future.


Iterate through a collection


Let's say that you want to perform some operations on each element of the collection. In the following example I want to print out each element of my list. I will use a for loop to do so.




val yourLuckyNumbers = List(23, 0, 512, 3, 4)

println("Your lucky numbers: ")
for (number <- yourLuckyNumbers) {
println(number)
}

Output would be:



Your lucky numbers:


23


0


512


3


4



Another example would be to execute an operation on each argument of Scala script (in this case the printout is reversed):




for (arg <- args) {
println(arg.reverse)
}

If you called the sample script: reverse.bat as:




reverse.bat abc efg

the output would be:



cba


gfe



Ranges: to and until


You can use a for loop also if you want to iterate over some range of values. Let's say that you want to iterate from 1 to 12:




for (i <- 1 to 12) {
println(i)
}

This one would generate the following output:



1


2


...


10


11


12



You can exclude the last value from iteration by replacing to with until. Let's say that you want to iterate from 0 to 59 using until:




for (i <- 0 until 60) {
println(i)
}

The output is obvious:



0


1


2


...


59



Filtering


If you want to iterate over a subset of collection you can use filters. Let's use a range and filters to generate even numbers from a range of 0 to 10:




for (i <- 0 to 10 if i % 2 == 0) {
println(i)
}

it's a shorter form of:




for (i <- 0 to 10) {
if (i % 2 == 0) {
println(i)
}
}

You can apply multiple filters. Let me generate numbers from 0 to 10 which are even and divisible by 3:




for (i <- 0 to 10
if i % 2 == 0
if i % 3 == 0) {
println(i)
}

Nested iterations


You can put multiple <- clauses separated with semicolons. This will tell Scala that loops are nested. Let's see the example below:




val multiDim = List(List(11, 12, 13),
List(21, 22, 23),
List(31, 32, 33))

for (
row <- multiDim;
element <- row
) println(element)

This actually behaves the same as:




val multiDim = List(List(11, 12, 13),
List(21, 22, 23),
List(31, 32, 33))

for ( row <- multiDim )
for (element <- row)
println(element)

Filtering and nested loops


You can use filtering in nested loops just like in normal loops. Let's see the following example:




val multiDim = List(List(11, 12, 13, 14),
List(21, 22, 23),
List(31, 32))

for (
row <- multiDim
if row.length > 2;
element <- row
if element % 2 == 0
) println(element)

In this example we have nested a loop which iterates over multiDim list. The outer loop will return only these lists which have more than two elements:




if row.length > 2;

For the inner loop it will return only even elements:




if element % 2 == 0;

We could implement this loop in a normal way as follows:




for (row <- multiDim if row.length > 2)
for (element <- row if element % 2 == 0)
println(element)

or:




for (row <- multiDim)
if (row.length > 2)
for (element <- row)
if (element % 2 == 0)
println(element)

As you can see you can save a lot of time if you know what is the best way to implement your code.


Comments and questions


I encourage you to comment and write questions regarding this post or loops in general at michaelflowersky at geekingspree.com. Thanks for passing by!


References



  1. Programming in Scala: A Comprehensive Step-by-Step Guide, 2nd Edition by Martin Odersky, Lex Spoon and Bill Venners


My recommendations!


Looking for something compact about Scala? Check out Scala for the Impatient by Cay Horstmann.






via Geeking spree feed ... http://feedproxy.google.com/~r/GeekingSpreeFeed/~3/B_Dy-TfJags/scala-for-loop-13