Updated March 20, 2023
Introduction to Break in Scala
Break in scala is a programming language that has seamlessly combined the object-oriented paradigm with the functional paradigm. The name Scala was coined from combining the two terms SCAlable and Language. But one of the aspects to note about the language is the exclusion of the most basic flow constructs like Break and Continue. Do you have any idea why the Scalable Language has done this? No, you say! Well, worry not, In this article, we touch upon exactly this. We try to analyze how to use break if we need to in our program with some examples. Later we will also touch upon the design behind not adding break as an implicit flow constructs in the language.
So although the language does not support the Break keyword as a language construct we can use the util.control.Breaks._ package to implement similar functionality.
Let us take a look at the syntax for implementing break,
Syntax:
import util.control.Breaks._
breakable {
<LOOP> {
<statements>
<condition> break; //Conditionally break out of loop
}
}
As seen from the syntax few things that are important here are,
- Importing the package and,
- enclosing the loop in the breakable function.
- Also, the obvious… a break statement.
A fun fact btw, the break statement here is a function call. But more on that later.
Flow Diagram
Moving forward, Let us now try to further understand by looking at how the execution works with the help of a flowchart. The Flowchart below figure depicts how a normal for loop functions. It starts with an initialization block. Below the block is a decision box that verifies if the specified conditions are met. Based on the output of the decision box one of the two routes is selected.
We are interested in what happens inside the “In loop code execution” block. A dotted line from the block represents a change of program flow due to the break statement.
The below figure shows the internals of how the “In loop code execution” functions in Scala. In the flowchart from Figure 2, there is a call to break function which in turn raises an exception. This exception is then handled by the breakable which alters the program flow. Alternatively, In Java break is a predefined construct in the language and instead of throwing an exception it will change the code flow similar to how goto does.
As seen in the flowchart control from the decision box (in Figure 1) comes to A in Figure 2. Also, control from B goes to the “Out of loop code execution” block above figure.
Working
Let us further look at how the break works in Scala by looking at the function internals. Breakable is a function that has a case to handle a breakException. Also, the break function throws a breakException.
Code:
def breakable(op: => Unit) {
try {
op
} catch {
case ex: BreakControl =>
if (ex ne breakException) throw ex
}
}
def break(): Nothing = { throw breakException }
One might start to wonder why is this done in the first place. Almost all languages have a break statement inbuilt in the language. So why have the language developers decided to not have break as a part of the arsenal? Well, there are a few reasons for that,
- other language constructs.
- Also, they create problems while interacting with closures.
- They do not mesh well with the function literals.
“You can read more on this in ‘Programming in Scala, Second Edition’, by Martin Odersky, Lex Spoon, and Bill Venners.”
Examples of Break in Scala
Let us take a look at a few examples to get an understanding of how this is done.
Example #1
This example demonstrates the usage of a break in a single loop.
Code:
import scala.util.control.Breaks._
object BreakExample extends App {
breakable {
for (index <- 1 to 10) {
println(index)
if (index >= 5) break
}
}
}
Output:
Explanation: As seen in the example, the for-loop is enclosed in the breakable block. For every iteration of the for loop, if loop checks if the index is less than or equal to 5, if the condition is valid then a call to break will be made which makes the program exit from the for loop. Output will be all the values of the index from 1 to 4.
Example #2
This example demonstrates the use of break-in Nested loops.
Code:
import scala.util.control.Breaks._
object BreakTests extends App
{
val listA = List(1, 2, 3);
val listB = List(5, 10, 15);
var itemA = 0;
var itemB = 0;
breakable
{
for (itemA <- listA)
{
println("" + itemA);
breakable
{
for (itemB <- listB)
{
println("- " + itemB);
if (itemB == 10) break;
}
}
}
}
}
Output:
Explanation: The program encounters a break statement inside the inner for loop. The usage is pretty similar to that in Example 1. In this case, when a break is encountered, the control will only exit the inner loop and not the outer loop. The functioning of the outer for loop will continue as expected. Observing the output makes it clear that whenever the value of itemB is 10 the for loop will be exited. Outer for loop goes through a complete iteration.
Example #3
How the break statement works in a while loop explained below.
Code:
import scala.util.control.Breaks._
object BreakTests extends App
{
var index = 0;
var sum = 0
breakable
{
while (index < 1000) {
sum += index
index +=1
println(sum);
if (sum > 10) break;
}
}
}
Output:
Explanation: This example is similar to Example 1, except a while loop has been used here to demonstrate working of break inside a while loop. Here a sum is computed and whenever the sum variable value goes above 10, a break is initiated.
Conclusion
So, in conclusion, Scala does not encourage to use explicit break statements. There are a lot of different mechanisms of how we can avoid using break statements. However, if the break is unavoidable you can use the Break package to get the task done.
Recommended Articles
This is a guide to Break in Scala. Here we discuss the syntax, flowchart, and working of break in scala along with the examples and its implementation. You may also look at the following articles to learn more-