For in Scala
object ForLoops {
def main(args: Array[String]): Unit = {
// The most basic type, with a single condition.
var i = 1
while (i <= 3) {
println(i)
i += 1
}
// A classic initial/condition/after for loop.
for (j <- 0 until 3) {
println(j)
}
// Another way of accomplishing the basic "do this N times" iteration
// is to use a range.
for (i <- 0 until 3) {
println(s"range $i")
}
// A while(true) loop will repeat until you break out of it or return
// from the enclosing function.
while (true) {
println("loop")
break
}
// You can also continue to the next iteration of the loop.
for (n <- 0 until 6) {
if (n % 2 == 0) {
continue
}
println(n)
}
}
}
In Scala, we have several ways to create loops:
The
while
loop is used for the most basic type of loop with a single condition.The
for
loop in Scala is more powerful and can be used in various ways. Here, we’ve used it with a range (0 until 3
) which is similar to the Gofor j := 0; j < 3; j++
loop.Scala doesn’t have a direct equivalent to Go’s
for i := range 3
. Instead, we use afor
loop with a range.For an infinite loop, we use
while(true)
. Note that Scala doesn’t havebreak
orcontinue
statements. To achieve similar functionality, you would typically use recursive functions or other control structures. Thebreak
andcontinue
shown in this example are just for illustration and won’t compile in actual Scala code.The last example shows how you might simulate a
continue
in Scala using an if-else structure.
To run this Scala program:
$ scalac ForLoops.scala
$ scala ForLoops
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
Remember that Scala encourages a more functional programming style, so while these imperative loops are possible, you might often see more functional approaches using methods like map
, filter
, and foreach
on collections.