Updated April 4, 2023
Introduction to Scala for Loop
For loops are one of the key flow constructs in any programming language. In case if you are looking for a place to find all the for loop examples in Scala then you have come to the right place. In this article, we will take a look into multiple ways using which one can use for loops in Scala. So let’s get started.
Flowchart:
An idea about the control flow during a for loop. As you can see after every iteration a conditional check is made. If the check is invalid the control goes to the out of loop code execution block.
Examples to Implement Scala for Loop
There are many ways in Scala in which one can iterate over elements. In this article, we will touch upon all these ways. So let’s start our journey with the syntax and examples for basic for loop in Scala.
Before starting, let us define a data structure that will be used in examples below:
val name_seq= Seq("eduCBA", "is", "good")
val num_seq = Seq(1, 2, 3)
Example #1 – Basic for loop
Syntax:
for(item <- List){
// Inner loop code
}
In the syntax, we are iterating over all the elements of a list. For each iteration value of one of the elements is sequentially placed in the item var. We can then use this item var for operating on it.
Code:
Print values of items in a list
object Demo {
def main(args: Array[String]) {
val name_seq= Seq("eduCBA", "is", "good")
val num_seq = Seq(1, 2, 3)
for (item <- name_seq) println(item)
for (item <- num_seq) {
println(item);
}
}
}
Output:
Explanation:
The output consists of print statements from 2 loop executions. The first 3 lines are the output of the “name_seq” sequence and the 3 lines after that are from the “num_seq”.
Example #2 – Basic for Loop with Conditions/Filters
Moving on we have a for loop with a filter. This is a mutation/ extension of the first type of for loop.
Syntax:
for(item <- List
if filter1; if filter2; ...)
{
// Inner loop code
}
Code:
object Demo {
def main(args: Array[String]) {
val item_seq = Seq(1, 2, 3, 4, 5, 6, 7, 8)
for( item <- item_seq
if item < 5; if item > 3 )
{
println("Filtered number is : " +item);
}
}
}
Output:
Explanation:
The filtered number is 4 from the sequence starting from 1 to 8. This is because of the filters. I.e the item should be less than 5 and it should be greater than 3. The only number that satisfies this filter is 4.
As seen in the example we can add multiple filters to the for loop.
Example #3 – forEach
This is one of the primary primitive that one can use to iterate over items in Scala.
Syntax:
List.forEach()
Code:
object Demo {
def main(args: Array[String]) {
val name_seq= Seq("eduCBA", "is", "good")
val num_seq = Seq(1, 2, 3)
name_seq.foreach(println)
name_seq.foreach(e => println(e.toUpperCase))
name_seq.foreach {
// A multiline example
name => println(name.toUpperCase)
}
}
}
Output:
Explanation:
The above output is a collection of outputs from 3 for loops. One which directly prints the items in the name_seq as it is and 2nd and 3rd convert the items into uppercase letters. The third example gives an example of writing multiline statements inside the forEach loop.
Example #4 – Using Generators
Generators are functions that can stop midway during execution and then start from the same point again once the execution is started. This is a big topic and will need an article in itself which is out of scope for this article.
Let us take a look at how generator functions can be used with for loops.
- Single Generator
Code:
object Demo {
def main(args: Array[String]) {
for (index <- 1 to 5)
println(index)
}
}
Output:
- Multiple generators
Code:
object Demo {
def main(args: Array[String]) {
val name_seq= Seq("eduCBA", "is", "good")
val item_seq = Seq(1, 2, 3, 4, 5, 6, 7, 8)
val result = for {
a <- name_seq
b <- item_seq
} yield (a, b)
println(result)
}
}
Output:
In this example, we have demonstrated the use of multiple generators in a single for loop.
Example #5 – Using Generators with Guard Statement
One can also add guard statements/ Filters in the generators. Let’s take a look at how this would work for single line and multiple line statements.
- Single line
Code:
object Demo {
def main(args: Array[String]) {
for (i <- 1 to 8 if i < 3) println(i)
}
}
Output:
- For multiple lines
We can have multiple guard statements similar to a for loop with multiple filters.
Code:
object Demo {
def main(args: Array[String]) {
for {
i <- 1 to 15
if i > 4
if i < 8
if i % 3 == 0
} println(i)
}
}
Output:
In the above example, there are multiple conditions that are applied to the generator. Conditions are also called as guard statements.
Example #6 – For Loop with yield Statements
Some of the examples below explore the usage of yield in the for loop.
Code:
object Demo {
def main(args: Array[String]) {
val name_seq= Seq("eduCBA", "is", "good")
val name_seq_2 = for (name <- name_seq) yield name.capitalize
println("" + name_seq_2);
}
}
Output:
We can similarly write for Loops with multiple lines by replacing the yield statement with a lambda function as done in the examples before.
Other ways of Iterating in the For Loop
- Until:
One can use until to specify the terminating condition for a loop. Let us take a look at the example
Code:
object Demo {
def main(args: Array[String]) {
val name_seq= Seq("eduCBA", "is", "good")
for (index <- 0 until name_seq.length) {
println(s"Position of ${name_seq(index)} is $index")
}
}
}
Output:
- zipWithIndex:
Another way to add a counter to the sequence is to use a zipWithIndex. zipWithIndex zips the list/ sequence with a counter value that starts with 0. Let us take a look at an example to understand it better,
Code:
object Demo {
def main(args: Array[String]) {
val name_seq= Seq("eduCBA", "is", "good")
for ((name, count) <- name_seq.zipWithIndex) {
println(s"Index: $count | Item: $name")
}
}
}
Output:
As seen in the output we get two values name and count. Count is the counter that will be generated by the use of zipWithIndex. One thing to note here is that zipWithIndex will always have a counter value starting from 0.
Conclusion
In this article, we demonstrated some of the ways for using For Loop in Scala. While this is not an exhaustive list but we are sure these are all that you would need. In case we have missed any, please do let us know and we will definitely add them in the list.
Recommended Articles
We hope that this EDUCBA information on “Scala for Loop” was beneficial to you. You can view EDUCBA’s recommended articles for more information.