For Loop in Scala
In Scala, For Loop can be used to
- execute a block of statements over a range of items
- execute a block of statements over a filtered range of items
- yield a filtered output from a range of items
- iterate over a collection
- execute a block of statements over a range by skipping some of the items
Scala For Loop with a Range
Following is the syntax of for loop that iterates for a range of items.
for( a <- range){
// set of statements
}
You can mention the range as b to c
for [b,c] or b until c
for [b,c).
Example 1 – Scala For Loop with Range
In this example, we take a range of 1 to 4 i.e., [1, 4] and execute a print statement for each of the elements in the range using for loop.
example.scala
object ForLoopExample {
def main(args: Array[String]) {
var a = 0
// for loop over a range
for( a <- 1 to 4){
println( "a: " + a )
}
}
}
Output
a: 1
a: 2
a: 3
a: 4
In this example, we take a range of 1 until 4 i.e., [1,4)
example.scala
object ForLoopExample {
def main(args: Array[String]) {
var a = 0
// for loop over a range
for( a <- 1 until 4){
println( "a: " + a )
}
}
}
Output
a: 1
a: 2
a: 3
Scala For Loop with a Filtered Range
Following is the syntax of for loop that iterates for a filtered range of items.
for( a <- range if boolean_expression){
// set of statements
}
You can mention the range as b to c
for [b,c] or b until c
for [b,c).
boolean_expression
has to evaluate to a true
or false
.
Example 2 – Scala For Loop with Filtered Range
In this example, we take a range of 1 to 20 i.e., [1, 20] and print only those elements that are exactly divisible by 5 using for with filtered range.
example.scala
object ForLoopExample {
def main(args: Array[String]) {
var a = 0
println("Printing multiples of 5 within the range 1 to 20")
// for loop over a filtered range
for( a <- 1 to 20 if a%5==0){
println( "a: " + a )
}
}
}
Output
Printing multiples of 5 within the range 1 to 20
a: 5
a: 10
a: 15
a: 20
In this example, we take a range of 1 until 4 i.e., [1,4)
Scala For Loop to Yield an output from Range
yield keyword is used to output a range from an input range and a condition.
Following is the syntax of for loop to yield output.
var output = for(a <- input_range if boolean_expression) yield a
output
is a vector that contains elements from input_range
satisfying the boolean_expression
.
boolean_expression
has to evaluate to a true
or false
.
Example 1 – For Loop Yield
In this example, we take a range of 1 to 20 i.e., [1, 20] and yield those values that are exactly divisible by 6 into a vector.
example.scala
object ForLoopExample {
def main(args: Array[String]) {
var a = 0
// yield with for loop
var output = for(a <- 1 to 20 if a%6==0) yield a
println(output)
}
}
Output
Vector(6, 12, 18)
Conclusion
In this Scala Tutorial, we learned about For Loop in Scala, and how to use it with Ranges, Filtered Ranges, etc., with the help of examples.