Scala For Loop
A Scala for loop can iterate over numeric ranges and collections. It can also filter values with guards, use multiple generators, iterate with an index, and produce a new collection with yield.
- 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
In Scala, this syntax is also called a for expression. Without yield, it performs an action for each value. With yield, it returns a collection containing the generated results.
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
}
The expression to the right of <- supplies the values. The loop variable receives one value during each iteration.
You can mention the range as b to c for [b,c] or b until c for [b,c).
1 to 4includes both 1 and 4.1 until 4includes 1 but excludes 4.
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
The next example uses until. The range starts at 1 and stops before 4, so the loop prints only 1, 2, and 3.
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 from 1 to 10
To run a Scala loop ten times, use the inclusive range 1 to 10.
object ForLoopOneToTen {
def main(args: Array[String]): Unit = {
for (number <- 1 to 10) {
println(number)
}
}
}
The loop executes once for every integer in the range, including 10.
Scala For Loop with a Custom Step
Use by to control the difference between consecutive range values. This is useful when a loop must skip numbers.
object ForLoopStepExample {
def main(args: Array[String]): Unit = {
for (number <- 2 to 10 by 2) {
println(number)
}
}
}
Output
2
4
6
8
10
A negative step can be used for a descending range.
for (number <- 5 to 1 by -1) {
println(number)
}
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.
The condition after if is called a guard. Values for which the guard evaluates to false are skipped.
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
More than one guard can be placed in a for expression. A value is processed only when all guards evaluate to true.
object MultipleGuardsExample {
def main(args: Array[String]): Unit = {
for {
number <- 1 to 30
if number % 2 == 0
if number % 3 == 0
} {
println(number)
}
}
}
Output
6
12
18
24
30
Scala For Loop with yield
The yield keyword transforms each generated value and returns the results in a collection. The result type normally follows the type of the source collection.
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.
When the input is a range, the yielded result is commonly an indexed sequence such as a Vector. When the input is a List, the result is normally a List.
Example 3 – Scala For Loop with yield and a Guard
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)
Transforming Values with Scala for/yield
The expression after yield does not have to return the original element. It can calculate a new value for every iteration.
object YieldSquaresExample {
def main(args: Array[String]): Unit = {
val squares = for (number <- 1 to 5) yield number * number
println(squares)
}
}
Output
Vector(1, 4, 9, 16, 25)
Scala For Loop over Collections
A Scala for loop can iterate directly over collections such as List, Vector, Set, and Map. A numeric range is not required.
Iterating over a Scala List
object ListForLoopExample {
def main(args: Array[String]): Unit = {
val languages = List("Scala", "Java", "Kotlin")
for (language <- languages) {
println(language)
}
}
}
Output
Scala
Java
Kotlin
Iterating over Scala Map Key-Value Pairs
A map element can be unpacked into its key and value directly in the generator.
object MapForLoopExample {
def main(args: Array[String]): Unit = {
val scores = Map("Asha" -> 92, "Ravi" -> 85)
for ((name, score) <- scores) {
println(s"$name: $score")
}
}
}
Scala For Loop with Index
Use zipWithIndex when both the element and its zero-based index are required. This is generally clearer than manually maintaining a mutable counter.
object ForLoopIndexExample {
def main(args: Array[String]): Unit = {
val colors = List("Red", "Green", "Blue")
for ((color, index) <- colors.zipWithIndex) {
println(s"$index: $color")
}
}
}
Output
0: Red
1: Green
2: Blue
To display positions starting from 1, print index + 1 instead of index.
Scala For Loop with Multiple Generators
A single for expression can contain multiple generators. The inner generator runs for every value produced by the outer generator, which is similar to nested loops.
object MultipleGeneratorsExample {
def main(args: Array[String]): Unit = {
for {
row <- 1 to 2
column <- 1 to 3
} {
println(s"row=$row, column=$column")
}
}
}
Output
row=1, column=1
row=1, column=2
row=1, column=3
row=2, column=1
row=2, column=2
row=2, column=3
Breaking Out of a Scala For Loop
Scala does not use a built-in break statement in the same way as Java. In most cases, express the stopping condition with collection operations such as takeWhile, find, or a filtered range.
For example, takeWhile limits the values before the loop begins:
object StopForLoopExample {
def main(args: Array[String]): Unit = {
for (number <- (1 to 10).takeWhile(_ < 5)) {
println(number)
}
}
}
This prints 1 through 4. Scala also provides scala.util.control.Breaks for imperative code, but condition-based collection operations are usually easier to read and compose.
Scala For Loop and Java For Loop Differences
A Java-style loop normally contains initialization, a Boolean condition, and an update expression. Scala usually iterates over a range or collection instead.
for (number <- 0 until 5) {
println(number)
}
The Scala range controls the starting value, stopping point, and step. This avoids a separate mutable loop counter in many cases.
Common Scala For Loop Mistakes
- Using
towhen the upper limit must be excluded: useuntilfor an exclusive upper bound. - Expecting
yieldto print values:yieldcreates a collection; useprintlninside the loop to produce console output. - Assuming every yielded range is a List: the resulting collection is based on the source collection and its builder.
- Using a mutable index unnecessarily: use
zipWithIndexwhen iterating over a collection with positions. - Trying to use Java-style
breakdirectly: prefer guards,takeWhile,find, or another collection operation.
Scala For Loop FAQs
What is the difference between to and until in a Scala for loop?
to includes the ending value, while until excludes it. Therefore, 1 to 4 produces 1, 2, 3, and 4, whereas 1 until 4 produces 1, 2, and 3.
How do I write a Scala for loop from 1 to 10?
Use for (number <- 1 to 10). The to range includes both endpoints, so the loop runs ten times.
How do I get the index in a Scala for loop?
Call zipWithIndex on the collection and unpack each pair: for ((value, index) <- values.zipWithIndex). The generated index starts at zero.
What does yield do in a Scala for loop?
yield evaluates an expression for each accepted loop value and collects the results. It changes the for statement from an iteration performed for side effects into an expression that returns a collection.
How can I stop a Scala for loop early?
Prefer limiting the input with operations such as takeWhile or finding the required element with find. The scala.util.control.Breaks utility is available when an imperative break is necessary.
Scala For Loop Tutorial Summary
In this Scala Tutorial, we learned how to use a Scala for loop with inclusive and exclusive ranges, custom steps, guards, collections, indexes, multiple generators, and yield. Use to when the upper endpoint must be included, until when it must be excluded, and yield when the loop should return transformed values.
TutorialKart.com