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:

while
   i < 5
do
   println(i)
   i += 1


while (i < 3) do
   println(i)
   i += 1

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

while (i < 3)
   println(i)
   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.

... this post is sponsored by my books ...