![]() |
VOOZH | about |
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: 👁 Image
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:
Output:
1 2 3 4 5
Break in Nested loop: We can also use break method in nested loop. For example:
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.