Scala While Loop

A Scala while loop repeatedly executes a block of statements while a Boolean condition remains true. It is useful when the number of iterations is not known before the loop starts.

In this tutorial, you will learn the syntax of the Scala while loop, how its condition is evaluated, how to update the loop variable, and how to avoid an infinite loop. The examples apply to both Scala 2 and Scala 3 unless noted otherwise.

Scala While Loop Syntax

The syntax of Scala while loop is

</>
Copy
 while(boolean_expression){
     statement(s)
 }

The boolean_expression must produce either true or false. Scala checks this condition before every iteration:

  1. Scala evaluates the loop condition.
  2. If the condition is true, the statements in the loop body run.
  3. After the body finishes, Scala evaluates the condition again.
  4. If the condition is false, execution continues with the statement after the loop.

Because the condition is checked before the body, a while loop can execute zero times. Any variable that controls the condition normally has to be updated explicitly inside the loop.

Scala 3 While Loop Syntax Without Braces

Scala 3 also supports an indentation-based form using the do keyword. The condition and behavior are the same as in the brace-based form.

</>
Copy
while condition do
  statements

For example, the following Scala 3 loop prints the values from 1 through 3.

</>
Copy
var number = 1

while number <= 3 do
  println(number)
  number += 1
1
2
3

Scala While Loop Example: Print Squares

In this example, we shall find the square of a number until it is less than 10 and print the result to the console.

example.scala

</>
Copy
object WhileLoopExample {
  def main(args: Array[String]) {
    var i=0
    while (i < 10){
      var square = i*i
      println(square)
      // update i
      i=i+1
    }
  }
}

Output

1
4
9
16
25
36
49
64
81

The loop starts with i equal to 0, calculates i * i, prints the square, and increments i. Therefore, the program itself also prints 0 before the values shown above, followed by the squares from 1 through 9.

Tracing the While Loop Condition and Counter

The important values during the first few iterations are:

i before iterationCondition i < 10Printed squarei after update
0true01
1true12
2true43
9true8110
10falseNot executedLoop ends

Avoiding an Infinite While Loop in Scala

If you forget to update the variable i inside the while loop, the loop becomes infinite loop and the program control will be trapped inside it. The control will never come out of the loop and no subsequent statements are executed ever.

For example, the following loop never changes count, so its condition remains true.

</>
Copy
var count = 1

while (count <= 5) {
  println(count)
  // Missing: count += 1
}

To prevent this problem, confirm that every path through the loop either changes the condition or deliberately exits the loop.

Using a While Loop with a Scala Collection

A while loop can process collection elements by maintaining an index. The index must remain within the collection bounds.

</>
Copy
val languages = Array("Scala", "Java", "Python")
var index = 0

while (index < languages.length) {
  println(languages(index))
  index += 1
}
Scala
Java
Python

This approach is valid, but collection operations such as foreach, map, and filter are often clearer when you do not specifically need mutable loop state or index-level control.

Scala While Loop Compared with a For Loop

Use a while loop when repetition depends on a condition that changes during execution. Use a for loop when iterating through a known range, collection, or sequence of values.

RequirementSuitable Scala construct
Repeat until a changing condition becomes falsewhile
Iterate through a numeric rangefor
Process every element in a collectionfor, foreach, or another collection operation
Maintain and modify explicit loop statewhile

Stopping a Scala While Loop Early

Scala does not provide a built-in break statement in the same style as Java. A common approach is to include the stopping requirement directly in the loop condition.

</>
Copy
var number = 1
var continue = true

while (number <= 10 && continue) {
  println(number)

  if (number == 4) {
    continue = false
  }

  number += 1
}
1
2
3
4

Scala also has scala.util.control.Breaks, but expressing the exit rule in the condition usually makes the control flow easier to follow.

Scala While Loop and Do-While Difference

A while loop checks its condition before executing the body, so it may run zero times. The traditional Scala 2 do-while form checks the condition after the body and therefore executes at least once.

</>
Copy
do {
  statements
} while (condition)

The traditional do-while construct is no longer part of Scala 3 syntax. In Scala 3, write equivalent logic using a while loop and suitable initial state.

Common Scala While Loop Mistakes

  • Not updating the counter: The condition never becomes false, producing an infinite loop.
  • Using the wrong comparison operator: Changing < to <= can add an unintended iteration.
  • Accessing an invalid collection index: Use index < collection.length, not index <= collection.length.
  • Expecting the body to run once: A while loop does not execute when its initial condition is false.
  • Using mutable looping unnecessarily: A for loop or collection operation may communicate the intent more directly.

Scala While Loop FAQs

Can a Scala while loop execute zero times?

Yes. Scala evaluates the condition before entering the loop body. If the condition is initially false, the body is skipped.

How do you write a while loop in Scala 3?

You can use braces as in earlier Scala versions, or use indentation syntax: while condition do, followed by an indented loop body.

Why does a Scala while loop become infinite?

A loop becomes infinite when its condition never evaluates to false. This commonly happens when the counter or other condition-controlling state is not updated.

Should I use a while loop or for loop in Scala?

Use while when repetition depends on mutable state or an open-ended condition. Use for when iterating through a range or collection.

Does Scala have a break statement for while loops?

Scala has no built-in break keyword equivalent to Java’s statement. You can include the exit requirement in the loop condition or use scala.util.control.Breaks when necessary.

Scala While Loop Editorial QA Checklist

  • Verify that every while-loop condition has the Boolean type.
  • Check that each counter or condition-controlling variable is updated on every required execution path.
  • Confirm that numeric boundaries produce the intended first and last iterations.
  • Match each displayed output with the initial value, condition, body, and update expression in its code example.
  • Use Scala 3 indentation syntax only with while condition do, and do not present the removed do-while syntax as Scala 3 code.

Summary of While Loops in Scala

In this Scala Tutorial, we learned what a while loop is, the syntax of while loop in Scala, and its usage with the help of examples. A Scala while loop checks its condition before each iteration, requires explicit state updates in many cases, and is most suitable when repetition is controlled by a changing condition rather than a fixed range.