Scala for Loop
The for loop allows you to write a loop control structure that executes a specified number of times.
Syntax
The syntax for a for loop in the Scala language is:
for (var x <- Range) {
statement(s);
}
In the above syntax, Range can be a numerical range represented by i to j, or i until j. The left arrow <- is used to assign values to the variable x.
Example
Here is an example using the i to j syntax (inclusive of j):
Example
object Test {
def main(args: Array[String]) {
var a = 0;
// for loop
for (a <- 1 to 10) {
println("Value of a: " + a);
}
}
}
The output of the above code is:
$ scalac Test.scala
$ scala Test
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 10
Here is an example using the i until j syntax (exclusive of j):
Example
object Test {
def main(args: Array[String]) {
var a = 0;
// for loop
for (a <- 1 until 10) {
println("Value of a: " + a);
}
}
}
The output of the above code is:
$ scalac Test.scala
$ scala Test
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
In a for loop, you can use semicolons (;) to set multiple ranges, which will iterate over all possible values of the given ranges. The following example demonstrates a loop with two ranges:
Example
object Test {
def main(args: Array[String]) {
var a = 0;
var b = 0;
// for loop
for (a <- 1 to 3; b <- 1 to 3) {
println("Value of a: " + a);
println("Value of b: " + b);
}
}
}
The output of the above code is:
$ scalac Test.scala
$ scala Test
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
for Loop with Collections
The syntax for a for loop with collections is as follows:
for (x <- List) {
statement(s);
}
In the above syntax, the List variable is a collection, and the for loop will iterate over all elements of the collection.
Example
The following example will loop over a collection of numbers. We use List() to create a collection. We will introduce collections in more detail in later chapters.
Example
object Test {
def main(args: Array[String]) {
var a = 0;
val numList = List(1,2,3,4,5,6);
// for loop
for (a <- numList) {
println("Value of a: " + a);
}
}
}
The output of the above code is:
$ scalac Test.scala
$ scala Test
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
for Loop Filtering
Scala can use one or more if statements to filter some elements.
Here is the syntax for using filters in a for loop.
``` for (var x <- List if condition1; if condition2...