Scala Loops

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

Programming languages provide various control structures that allow 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

The Scala language provides the following loop types. Click the links to view details of each type.

Loop Type Description
while loop Runs a series of statements. If the condition is true, it repeats until the condition becomes false.
do...while loop Similar to the while statement, except that it executes the loop's code block once before checking the loop condition.
for loop Used to repeatedly execute a series of statements until a specific condition is met, generally implemented by incrementing a counter value after each loop iteration.

Loop Control Statements

Loop control statements change the execution order of your code, and through them you can implement code jumps. Scala has the following loop control statements:

Scala does not support break or continue statements, but since version 2.8 it provides a way to break out of loops. Click the link below for details.

Control Statement Description
break statement Breaks the loop

Infinite Loops

If the condition is always true, the loop becomes an infinite loop. We can use the while statement to implement an infinite loop:

Example

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

After the above code is executed, the loop will run forever. You can use Ctrl + C to interrupt the infinite loop.

Other Extensions