Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Loops

Scala Loops

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

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

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

Loop structure


Loop types

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

Loop types Description
while loop Runs a series of statements repeatedly while a condition is true, until the condition becomes false.
do...while loop Similar to the while statement, the difference being that the loop body is executed once before the loop condition is checked.
for loop Used to repeatedly execute a series of statements until a specific condition is reached, usually implemented by incrementing a counter after each iteration.

Loop control statements

Loop control statements change the execution order of your code, allowing you to jump within it. 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 a loop. Click the following link for details.

Control statement Description
break statement Breaking a Loop

Infinite loop

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

Example

object

Test

{

   

def

main

(

args

:

Array

[

String

]

)

{

     

var

a

=

10

;

     

// infinite loop

     

while

(

true

)

{

         println

(

"The value of a is: "

)

;

     

}

   

}

}

After the above code runs, the loop will execute forever; you can press Ctrl + C to interrupt the infinite loop.