Scala Loops
Sometimes, we may need to execute the same block of code multiple times. Generally, statements are executed in sequence: 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 the flowchart of loop statements in most programming languages:
Loop Types
The Scala language provides the following types of loops. Click on the links to view the details of each type.
Loop Type | Description |
---|---|
while loop | Executes a series of statements repeatedly as long as the condition is true, until the condition becomes false. |
do...while loop | Similar to the while statement, the difference is that it executes the loop's code block once before checking the loop condition. |
for loop | Used to repeat a series of statements until a specific condition is met, usually achieved by incrementing the counter's value after each loop iteration. |
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 since version 2.8, it has provided a way to break out of a loop. Click on the following links for details.
Control Statement | Description |
---|---|
break statement | Breaks out of a loop |
Infinite Loops
If the condition is always true, the loop will become an infinite loop. We can implement an infinite loop using a while statement:
Example
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 run indefinitely, and you can interrupt the infinite loop using the Ctrl + C keys.