In Scala, we use a break statement to break the execution of the loop in the program. Scala programming language does not contain any concept of break statement(in above 2.8 versions), instead of break statement, it provides a break method, which is used to break the execution of a program or a loop. Break method is used by importing scala.util.control.breaks._ package. Flow Chart:
Syntax:
// import package
import scala.util.control._
// create a Breaks object
val loop = new breaks;
// loop inside breakable
loop.breakable{
// Loop starts
for(..)
{
// code
loop.break
}
}
or
import scala.util.control.Breaks._
breakable
{
for(..)
{
code..
break
}
}
For example:
Scala
import scala.util.control.Breaks. _
object MainObject
{
def main(args : Array[String])
{
breakable
{
for (a <- 1 to 10 )
{
if (a == 6 )
break
else
println(a);
}
}
}
}
|
Output:
1
2
3
4
5
Break in Nested loop: We can also use break method in nested loop. For example:
Scala
import scala.util.control. _
object Test
{
def main(args : Array[String])
{
var num 1 = 0 ;
var num 2 = 0 ;
val x = List( 5 , 10 , 15 );
val y = List( 20 , 25 , 30 );
val outloop = new Breaks;
val inloop = new Breaks;
outloop.breakable
{
for (num 1 <- x)
{
println(" " + num 1 );
inloop.breakable
{
for (num 2 <- y)
{
println(" " + num 2 );
if (num 2 == 25 )
{
inloop.break;
}
}
}
}
}
}
}
|
Output:
5
20
25
10
20
25
15
20
25
Explanation: In the above example, the initial value of both num1 and num2 is 0. Now first outer for loop start and print 5 from the x list, then the inner for loop start its working and print 20, 25 from the y list, when the controls go to num2 == 25 condition, then the inner loop breaks. Similarly for 10 and 15.