Programs

Scala For Loop | For Loop in Scala: Explained

In Scala, a for-loop is also known as for-comprehensions. It can be used to iterate, filter, and return a rehearsed collection. The for-comprehension looks quite similar to a for-loop in imperative languages; however, the difference is that it puts together a list of the results of alliterations.

There are several forms of for-loop in Scala, which are as described below:

For-Loop with Ranges

Syntax

The most uncomplicated syntax of a for-loop with ranges in Scala is as shown below:

for( var x <- Range ){

   statement(s);

}

As depicted above, the Range could be any range of numbers, represented as i to j or sometimes like i until j. The left-arrow ← operator is known as a generator because it generates individual values from a range.

Alternatively, one can also also use the syntax:

for(w <- range){

// Code..

}

Here, w is a variable, the left-arrow sign ← operator is the generator, and the range is the value which holds the starting and the ending values. The range is represented by using either i to j or i until j.

Scala For-Loop Example Using the Keyword ‘to’

Using ‘to’ with for-loop includes both the starting and the ending values. In the example shown below, we can use ‘to’ for printing values between 0 to n. In other words, the loop starts from 0 and ends at 10, which means we can print page numbers 0 to 10.

// Scala program to illustrate how to 

// create for loop using to 

object Main 

    def main(args: Array[String]) 

    { 

        println(“The value of w is:”); 

        // Here, the for loop starts from 0 

        // and ends at 10 

        for( w <- 0 to 10) 

        { 

            println(w); 

        } 

    } 

Output:

In the example shown above, the value of w is:

0

1

2

3

4

5

6

7

8

9

10

Read: Top 10 skills to become a full stack developer

Scala For-Loop Example Using the Keyword ‘until’

The difference between using until and to is; to includes the starting and the ending values given in a range, whereas until excludes the last value of the given range. In the for-loop example illustrated below, we can use until to print values between 0 to n-1. In other words, the loop starts at 0 and ends at n-1, which comes out to 9. So, we can print page numbers 0 to 9.

// Scala program to illustrate how to

// create for loop using until

object Main 

{

    def main(args: Array[String])

    {

        println(“The value of w is:”);

        // Here, the for loop starts from 0 

        // and ends at 10

        for( w <- 0 until 10)

        {

            println(w);

        }

    }

}

Output:

In the example shown above, the value of w is:

0

1

2

3

4

5

6

7

8

9

Also Read: Python vs Scala 

Multiple Values in For-Loop

We can also use multiple ranges in a single for-loop. These ranges are separated using a semicolon (;). Let us understand this with the help of an illustration. In the example given below, we have used two different ranges in a single loop, i.e., w <- 0 to 3; z <- 8 until 10.

// Scala program to illustrate how to

// create multiple ranges in for loop

object Main

{

    def main(args: Array[String]) 

    {

          

    // for loop with multiple ranges

        for( w <- 0 to 3; z<- 8 until 10 )

        {

            println(“Value of w is :” +w);

            println(“Value of y is :” +z);

        }

    }

}

Output:

Value of w is:0

Value of y is:8

Value of w is:0

Value of y is:9

Value of w is:1

Value of y is:8

Value of w is :1

Value of y is:9

Value of w is:2

Value of y is:8

Value of w is:2

Value of y is:9

Value of w is:3

Value of y is:8

Value of w is:3

Value of y is:9

Checkout: Full Stack Developer Salary in India

For-Loop with Collections

In Scala, we can use for-loop to efficiently iterate collections like list, sequence, etc., either by using a for-each loop or a for-comprehensions loop. The syntax of a for-loop with collections in Scala is as shown below:

Syntax

for( var x <- List ){

   statement(s);

}

Here, the variable list is a collection type with a list of elements and a for-loop iterates through all the elements returning one element in x variable at a time.

Let us look at the demo program given below to understand a for-loop with collections. In the illustration, we have created a collection using the List variable to list authors based on their ranks.

// Scala program to illustrate how to

// use for loop with collection

object Main

{

    def main(args: Array[String])

    {

        var rank = 0;

        val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // For loop with collection

        for( rank <- ranklist){

            println(“Author rank is : ” +rank);

        }

    }

}

Output:

Author rank is: 1

Author rank is: 2

Author rank is: 3

Author rank is: 4

Author rank is: 5

Author rank is: 6

Author rank is: 7

Author rank is: 8

Author rank is: 9

Author rank is: 10

For-Loop with Filters

For-loop in Scala allows you to filter elements from a given collection using one or more if statements in for-loop. Users can also add more than one filter to a ‘for’ expression using semicolons (;) to separate them. Listed below is the syntax for for-loop with filters.

Syntax

for( var x <- List

      if condition1; if condition2…

   ){

   statement(s);

}

Let us understand this better with the help of an example. The illustration given below uses two filters to segregate the given collection. For instance, in the sample below, the filters eliminate the list of authors with ranks greater than 2 and less than 7.

// Scala program to illustrate how to

// use for loop with filters

object Main

{

    def main(args: Array[String]) 

    {

        var rank = 0;

        val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // For loop with filters

        for( rank <- ranklist

        if rank < 7; if rank > 2 )

        {

            println(“Author rank is : ” +rank);

        }

    }

}

Output:

Author rank is: 3

Author rank is: 4

Author rank is: 5

Author rank is: 6

For-Loop with Yield

In Scala, the loop’s return value is stored in a variable or may return through a function. To do this, you should prefix the body of the ‘for’ expression with the keyword yield. Listed below is the syntax for for-loop with yield.

Syntax

var retVal = for{ var x <- List

   if condition1; if condition2…

}

yield x

Note − The curly braces list the variables and conditions, and retVal is a variable where all the values of x will be stored in the form of collection.

Let us understand this better with the help of an illustration. In the example given below, the output is a variable where all the rank values are stored in the form of a collection. The for-loop displays only the list of authors whose rank is greater than 4 and less than 8.

// Scala program to illustrate how to

// use for loop with yields

object Main

{

    def main(args: Array[String])

    {

        var rank = 0;

        val ranklist = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

          

        // For loop with yields

        var output = for{ rank <- ranklist

                    if rank > 4; if rank != 8 }

                    yield rank

          

        // Display result

        for (rank <- output)

        {

            println(“Author rank is : ” + rank);

        }

    }

}

Output:

Author rank is: 5

Author rank is: 6

Author rank is: 7

Author rank is: 9

Author rank is: 10

Conclusion 

If you’re interested to learn more about full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

We hope this helps!

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
ENROLL TODAY

Leave a comment

Your email address will not be published.

Accelerate Your Career with upGrad

Our Popular Software Engineering Courses

×