Javatpoint Logo
Javatpoint Logo

Scala for loop

In scala, for loop is known as for-comprehensions. It can be used to iterate, filter and return an iterated collection. The for-comprehension looks a bit like a for-loop in imperative languages, except that it constructs a list of the results of all iterations.

Syntax

In the above syntax, range is a value which has start and end point. You can pass range by using to or until keyword.


Scala for-loop example by using to keyword

Output:

1
2
3
4
5
6
7
8
9
10

In the below example, until is used instead of to. The major difference between until and to is, to includes start and end value given in the range, while until excludes last value of the range. So, the below example will print only 1 to 9.

Scala for-loop Example by using until keyword

Output:

1
2
3
4
5
6
7
8
9

It is helpful to apply until keyword when you are iterating string or array, because array range is 0 to n-1. until does not exceed to n-1. So, your code will not complain of upper range.


Scala for-loop filtering Example

You can use for to filter your data. In the below example, we are filtering our data by passing a conditional expression. This program prints only even values in the given range.

Output:

2
4
6
8
10

Scala for-loop Example by using yield keyword

In the above example, we have used yield keyword which returns a result after completing of loop iterations. The for use buffer internally to store iterated result and after finishing all iterations it yields the final result from that buffer. It does not work like imperative loop.

Output:

1
2
3
4
5
6
7
8
9
10

Scala for-loop in Collection

In scala, you can iterate collections like list, sequence etc, either by using for each loop or for-comprehensions.

Let's see an example.

Scala for- loop Example for Iterating Collection

Output:

1
2
3
4
5
6
7
8
9
10

Scala for-each loop Example for Iterating Collection

In the below code we have use three approaches of for-each loop. You can implement any of them according to your need.

Output:

1
2
3
4
5
6
7
8
9
123456789
1 2 3 4 5 6 7 8 9

Scala for-loop Example using by keyword

In the above example, we have used by keyword. The by keyword is used to skip the iteration. When you code like: by 2 it means, this loop will skip all even iterations of loop.

Output:

1
3
5
7
9
Next TopicScala Break




Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


B.Tech / MCA