For loop. In Scala 3.3 programs we usually act upon values in Lists. We can loop over these elements with "for" to act upon individual elements.
Loop notes. With for, we can enumerate a collection like a list. We can use the "to" method to advance through a range of numbers. We must choose the best loop.
For example. Let us begin with a for-loop that enumerates a list. We create a list with 3 strings in it. Then we use the for-each loop on the list.
Tip The syntax for a for-each loop in Scala is similar to that for Java. The language handles most of the iteration for us.
Detail We use the val keyword for the "ids" list, as we do not need to reassign it—we just loop over its contents.
object Program {
def main(args: Array[String]): Unit = {
// A list with 3 elements.
val ids = List("a1", "b2", "c3")
// Use a for-each loop over all the elements in the list.// ... Print the strings.
for (id <- ids) {
println(id)
}
}
}a1
b2
c3
For to. Here we introduce a for-to loop. We use the to-keyword to specify to what number the loop advances. Once an iteration is past 5, the loop here terminates.
object Program {
def main(args: Array[String]): Unit = {
// Use a for-to loop to iterate over a range of numbers.// ... Start at 0 and continue until 5.
for (i <- 0 to 5) {
println(i)
}
}
}0
1
2
3
4
5
For until. With a for-loop we can also use the "until" keyword. To and until are methods that return an enumeration of numbers. Until() stops one number before the final number.
object Program {
def main(args: Array[String]): Unit = {
// With until, the final number is not included.// ... It is an exclusive bound.
for (i <- 100 until 105) {
println(i)
}
}
}100
101
102
103
104
For to, until syntax. Sometimes a program is clearer to read (or understand) with more exact syntax. Scala's syntax is flexible. We can omit, or add, parentheses in for-to and until loops.
object Program {
def main(args: Array[String]): Unit = {
// Use parentheses around with to method.
for (i <- 0.to(3)) {
println(s"for to $i")
}
// Use parentheses with until.
for (i <- 0.until(3)) {
println(s"for until $i")
}
}
}for to 0
for to 1
for to 2
for to 3
for until 0
for until 1
for until 2
Ranges. We can directly loop over the numbers in a Range. The first argument to Range is the start, the second is the exclusive end. The third, optional argument is the step.
Tip The to() and until() methods return ranges. The for-loop can also loop over a stored local range val.
object Program {
def main(args: Array[String]): Unit = {
// Loop over the numbers in a range.
for (i <- Range(5, 8)) {
println(s"range1 $i")
}
// Loop with a step of 2.
for (i <- Range(0, 5, 2)) {
println(s"range2 $i")
}
// A decrement for-loop.// ... Step is negative 1.
for (i <- Range(10, 5, -1)) {
println(s"range3 $i")
}
}
}range1 5
range1 6
range1 7
range2 0
range2 2
range2 4
range3 10
range3 9
range3 8
range3 7
range3 6
While. This loop continues until the condition is not true. Here we begin with a var assigned to 3. This is the iteration variable, and it cannot be constant.
Then We loop while "i" is greater than or equal to zero. We decrement its value at the end of each iteration.
object Program {
def main(args: Array[String]): Unit = {
// Begin at 3.// ... Use var to have a mutable variable.
var i = 3
// Continue looping while "i" is greater than or equal to zero.
while (i >= 0) {
println(i)
// Decrement.
i -= 1
}
}
}3
2
1
0
While true. Sometimes we want a loop to repeat indefinitely. With a while-true loop this is possible. This program continues looping until a random number less than or equal to 0.1 appears.
object Program {
def main(args: Array[String]): Unit = {
// Call test method.
test()
}
def test(): Unit = {
// Print random numbers in a loop.
while (true) {
val rand = Math.random()
// Return if random number is too small.
if (rand <= 0.1) {
return
}
println(rand)
}
}
}0.5623560178530611
0.8956585369821868
0.4589158906009855
0.25810376023585613
0.6010527197089275
Summary. Loops are often not the most elegant programming construct. But they are effective. We have many for-loops available in the Scala language.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 15, 2023 (edit).