By Alvin Alexander. Last updated: February 29, 2024
Scala 2 has both while
loops and do
/while
loops, but note that Scala 3 eliminated the do
/while
syntax.
Here’s the general Scala 2 while
and do
/while
syntax:
// while loop
while(condition) {
statement(a)
statement(b)
}
// do-while (only available in Scala 2)
do {
statement(a)
statement(b)
}
while(condition)
Scala 'while' loop syntax
For more details, here’s a complete example of a while
loop that shows how to increment an integer:
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 the Scala 2 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.
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |
Summary
If you get into functional programming, you won’t use while
loops — 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).