Scala while and do/while loops (syntax, examples)

Once I got into functional programming I generally quit using while loops and do/while loops in Scala, but the language has both of them. Here’s the general syntax:

// while loop
while(condition) {
    statement(a)
    statement(b)
}

// do-while
do {
   statement(a)
   statement(b)
} 
while(condition)

Scala while loop syntax

Here’s an example of a while loop:

var i = 0
while (i < 3) {
    println(i)
    i += 1
}

The REPL shows that result:

scala> var i = 0
i: Int = 0

scala> while (i < 3) {
     |     println(i)
     |     i += 1
     | }
0
1
2

Scala do/while loop syntax

Similarly, here’s an example of a do/while loop:

var i = 0
do {
    println(i)
    i += 1
}
while (i < 0)

Again the REPL shows that result:

scala> var i = 0
i: Int = 0

scala> do {
     |     println(i)
     |     i += 1
     | }
     | while (i < 0)
0

Notice that the do loop prints 0 even though the test condition immediately fails. This is how a do/while loop works: it runs its loop before it runs its first test.

Summary

As mentioned, you don’t use these loops in functional programming (FP) — because you don’t use var fields in FP — but Scala while loops and do/while loops still have a place in OOP (object-oriented programming).