English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Scala Loops

Sometimes, we may need to execute the same block of code multiple times. Generally, statements are executed in order: the first statement in a function is executed first, followed by the second statement, and so on.

Programming languages provide various control structures for more complex execution paths.

Loop statements allow us to execute a statement or a group of statements multiple times. Below is a flowchart of loop statements in most programming languages:


Loop Types

Scala provides the following types of loops. Click the link to view the details of each type.

Loop TypesDescription
while LoopExecute a series of statements, and if the condition is true, it will repeat until the condition becomes false.
do...while LoopSimilar to the while statement, the difference is that the code block of the loop is executed once before the loop condition is checked.
for LoopUsed to repeat a series of statements until a specific condition is met, usually achieved by increasing the counter's value after each loop completion.

Loop Control Statements

Loop control statements change the execution order of your code, allowing you to implement code jumps. Scala has the following loop control statements:

Scala does not support break or continue statements, but from 2.8 Version introduced a way to break out of loops, click the following link to view details.

Control StatementsDescription
break StatementBreak the Loop

Infinite Loop

If the condition is always true, the loop will become an infinite loop. We can implement an infinite loop using the while statement:

object Test {
   def main(args: Array[String]) {
      var a = 10;
      // Infinite Loop
      while(true){
         println("The value of a is ": + a);
      }
   }
}

After executing the above code, the loop will continue indefinitely. You can use Ctrl + Press the C key to break out of an infinite loop.