Scala 3 ‘while’ loop syntax and examples

Here are a few examples of the Scala 3 while loop syntax.

Scala 3 while/do syntax

First, here are some one-line examples. This is the preferred syntax, using the while/do keywords.

while i >= 0 do i = f(i)

You can also use these styles, if you prefer:

while (i >= 0) do i = f(i)
while (i >= 0) { i = f(i) }

Scala 3 multiline while/do syntax

These examples show the multiline syntax for Scala 3 while loops. First, here’s the preferred while/do syntax:

   i < 5
   i += 1

while (i < 3) do
   i += 1

You can also use this multiline syntax, if you prefer:

while (i < 3)
   i += 1

In all of those examples, i is assumed to be a mutable variable, i.e., defined as a var. Also, I first started creating this page after seeing this Scala 3/Dotty page.

In summary, if you wanted to see how to use the Scala 3 while loop syntax, I hope these examples are helpful.