How to Program For Loop in Scala

Scala

Loops are important aspect of any programming language. Scala offers a rich set of functionality with for loop construct. In this article we are going to discuss about the syntax and different usage patterns of the for loops in Scala.

For loop in Scala with Counters

In Java you might have seen for loops with following syntax:

for(int i=1; i<=10; i++){
    System.out.println(i);
}

Output of above code is:

1
2
3
4
5
6
7
8
9
10

Scala also supports similar loops with the exception that you don't have to explicitly define the termination criterion and increment. Scala accepts the loop values as a range:

for (i <- 1 to 10) {
 Console.println(i);
}

Output of above code is:

1
2
3
4
5
6
7
8
9
10

Notice that you need not specify the type of i. Also you use <- operator to assign values to loop variable i. If you prefer you could specify data type of i:

for (i:Int <- 1 to 10) {
 Console.println(i);
}

For loop in Scala with collections

To iterate over a Java collection you have following syntax of for loop:

List<String> list=new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");

for(String str: list){
    System.out.println(str);
}

Output of above code snippet is:

a
b
c
d

Similarly in Scala you could iterate over a collection using following syntax of for loop:

val list=List("a","b","c","d");
for (str <- list) {
 Console.println(str);
}

Output of above code snippet is:

a
b
c
d

Here again you use <- operator assign each value of list variable to loop variable i.

For loop in Scala with conditions/filters

You could also specify conditions in Scala for loops

val list=List(1,2,3,4,5,6,7,8,9,10);
for(i <- list
    if(i>3)
    if(i%2==0)){
    
    Console.println(i);
}

Output of above code is:

4
6
8
10

Here we are specifying two conditions. First condition is:

if(i>3)

This condition imposes a restriction that i should be more than 3. After first condition is validated, i is checked with second condition:

if(i%2==0)

This condition validates if i is an even number. Once i passes both if conditions it is printed to console.

For loop in Scala with return values (using yield keyword)

We could also return values form for loops in Scala. Consider following code snippet:

val list=List(1,2,3,4,5)
val result=for(i <- list) yield {
    i+10;
}
Console.println(result)

Output of above code is:

List(11, 12, 13, 14, 15)

In the above code we take each value of list and add 10 to it. Using the keyword yield we could return each modified value of i and store it in a collection result. yield takes each value of i, performs some logic on it inside the body of for loop and returns the modified value.

References

  1. http://docs.scala-lang.org/cheatsheets/