Home »
Scala
How to break a loop in Scala?
By IncludeHelp Last updated : October 10, 2024
Loops in Scala: A loop is a statement that can execute a block of code multiple times based on some condition.
In Scala, there are three types of loops,
- for loop
- while loop
- do...while loop
How to break a loop?
To break a loop in Scala, we use the break statements as there is no direct break statement instead, there is a break method that is used to break a loop in Scala.
The break method needs to be imported using:
import scala.util.control.Breaks._
Syntax
The following syntax is used to break a loop,
var loop = new breaks;
Loop.breakable{
loop(){
//loop body
Loop.break;
}
}
Break a for loop
The for loop is used to execute a block of code multiple times in a program.
Example
// Program to break a for loop in Scala
import scala.util.control._
object MyClass {
def main(args: Array[String]) {
var loop = new Breaks;
loop.breakable{
for(i <- 1 to 10){
println(i*5);
// the loop will break at i = 6
if(i == 6){
loop.break;
}
}
}
}
}
Output:
5
10
15
20
25
30
In the above code, we have displayed how to break a for loop using the break method. We have created a breakable block of code using the object of Breaks class, the object named loop can create a block in which the break statement is applied. In the breakable, we have a for loop which runs from 1 to 10 and returns i*5, but we have used the break statement at with condition. This condition will be true when i = 6 and the flow of code breaks out of the loop at the iteration.
Break a while loop
The while loop in Scala is used to run a block of code multiple numbers of times. The number of executions is defined by an entry condition.
The break method can also be used to break out of a while loop.
Example
// Program to break a while loop in Scala
import scala.util.control._
object MyClass {
def main(args: Array[String]) {
var loop = new Breaks;
var i = 0;
loop.breakable{
while(i < 50){
println(i)
i+= 5
// the loop will break at i > 30
if(i > 30){
loop.break;
}
}
}
}
}
Output:
0
5
10
15
20
25
30
Break a do while loop
The do...while loop in Scala is used to run a block of code multiple numbers of time. The number of executions is defined by an exit condition.
The break method can also be used to break out of a do...while loop.
Example
// Program to break a do...while loop in Scala
import scala.util.control._
object MyClass {
def main(args: Array[String]) {
var loop = new Breaks;
var i = 0;
loop.breakable{
do{
println(i)
i+= 5
// the loop will break at i > 30
if(i > 30){
loop.break;
}
}
while(i < 50)
}
}
}
Output:
0
5
10
15
20
25
30