What are 'do while' loops in Scala?

In usual execution, the code is executed sequentially, line-by-line. Loops in Scala are control structures that allow users to run a block of code multiple times.

Do-while loop

The do-while loop repeatedly executes a block of code while the given condition stays true. It is different from the while loop in that it checks the condition after running the block of code.

Every do-while loop runs at least once, i.e. the block of code is executed, the condition is checked to run it again. If the condition holds true, it loops another time, otherwise, the loop execution terminates.

Syntax

do {
   //statement(s);
} 
while(condition);

Code

The following code shows an example of do-while loop in Scala where the value of the variable, myVal, is incremented and printed each time in the loop until its value becomes 5 after which it terminates since the loop condition evaluates to False.

object Educative
{
def main(args:Array[String]) {
// Local variable declaration:
var myVal = 0;
// do-while loop
do {
myVal = myVal + 1;
println(myVal);
}
while( myVal < 5 );
}
}

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved