Scala for loop

Tags: ,

In this post, we list the common ways of for loop in Scala programming. 

Scala for loop with ranges

The simplest syntax of for scala loop with ranges is as follows:

 i to j can also be replaced with other generators such as  i until j.  See the following example:

The output is:

value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5

Scala for loop with multiple ranges

We can use multiple ranges separated by semicolon (;) within scala for loop. In this case, the for loop will iterate through all the possible computations of the given ranges. The following code shows example  of using two ranges, we can also use more than two ranges. 

The output is:

Value of a: 1
Value of b: 1
Value of a: 1
Value of b: 2
Value of a: 1
Value of b: 3
Value of a: 2
Value of b: 1
Value of a: 2
Value of b: 2
Value of a: 2
Value of b: 3
Value of a: 3
Value of b: 1
Value of a: 3
Value of b: 2
Value of a: 3
Value of b: 3

Scala for Loop with List

The following is the syntax of scala for loop with collections or list.

Here, the List variable is a collection type having a list of elements and the for loop iterates all the elements and returns one element  stored in the e variable at a time.

See the following example showing how to for loop a Scala List.

The output:
value of a: 1
value of a: 2
value of a: 3

 

Scala for loop with guards 

Scala’s for loop allows to filter out some elements using one or more if statement(s). The code below is the syntax of for loop along with filters (guards). To add more than one filter to a ‘for’ expression, separate the filters with semicolons(;).

See the following example:

The output is:

Value of a: 1
Value of a: 2

Scala for loop with yield

The output:

Value of x: 1
Value of x: 2
Value of x: 4

Scala for loop, yield, and guards (for loop ‘if’ conditions)

This is another example:

By using the “if x > 2” guard condition, we limit the Array with only the three elements shown above.

Scala for loop on collection using foreach

A common way to iterate over a Scala List is using the foreach method. Here’s a quote about foreach from the book Programming in Scala:

foreach takes a procedure — a function with a result type Unit — as the right operand. It simply applies the procedure to each List element. The result of the operation is again Unit; no list of results is assembled.

The following example shows how to use foreach to print every item in a List:

This next example shows a way to sum all the elements in a list using the foreach:

Scala call foreach for Java List

If you have a java ArrayList, you can’t use foreach, as it is not defined in the the Java List.  However, we can use the implicit conversion to call foreach on Java’s ArrayList. See the following example: