Scala - break Statement



The break statement in Scala is used to terminate the loop immediately. While Scala does not have a built-in break keyword like some other languages. But you can achieve similar functionality using the Breaks class provided in scala.util.control package.

Syntax

Following is the syntax to use break statement −

import scala.util.control.Breaks.

breakable {
   for (var x <- Range) {
      if (condition) {
         break // terminate the loop
      }
      statement(s)
   }
}

Example of Scala break Statement

Try the following example program to understand loop with break −

import scala.util.control.Breaks._

object Demo {
   def main(args: Array[String]) {
      var a = 0;

      // for loop execution with a range and break logic
      breakable {
         for (a <- 1 to 10) {
            if (a == 5) {
               break // terminate the loop
            }
            println("Value of a: " + a)
         }
      }
   }
}

The above code shows how to use break within a for loop to terminate it when a = 5.

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command

>scalac Demo.scala
>scala Demo

Output

Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4

In the example above, the loop terminates when a is 5, after reaching the break statement.

Breaking Nested Loops

Existing break has an issue while using for nested loops. Just in case to use break for nested loops, follow this method. This is an example program for breaking nested loops.

Example

import scala.util.control.Breaks._

object NestedBreakDemo {
   def main(args: Array[String]) = {
      breakable {
         for (i <- 1 to 3) {
            for (j <- 1 to 3) {
               if (i == 2 && j == 2) {
                  break // terminate the outer loop
               }
               println(s"i = $i, j = $j")
            }
         }
      }
   }
}

Save the above program in NestedBreakDemo.scala. The following commands are used to compile and execute this program.

Command

\>scalac NestedBreakDemo.scala
\>scala NestedBreakDemo

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1

In this example, the break statement terminates the outer loop when both i and j are equal to 2.

Conditional Break in for Loop

The break statement can also be used within the conditional statement to break a for loop.

Example

In the following example, we are using break inside the conditional statement −

import scala.util.control.Breaks._

object ConditionalBreakDemo {
   def main(args: Array[String]) = {
      breakable {
      for (a <- 1 to 10) {
         if (a % 2 == 0) {
            break // terminate the loop when a is even
         }
         println("Value of a: " + a)
         }
      }
   }
}

Save the above program in ConditionalBreakDemo.scala. The following commands are used to compile and execute this program.

Command

\>scalac ConditionalBreakDemo.scala
\>scala ConditionalBreakDemo

Output

Value of a: 1

In this example, the for loop terminates as soon as it encounters an even number.

Alternatives to Using break

In Scala, there are various alternatives to using the break statement. Here are a few −

1. Using Return from a Function

You can use return to exit from the loop by encapsulating the loop inside a function.

object ReturnBreakDemo {
   def main(args: Array[String]) = {
      def loopWithReturn(): Unit = {
         for (a <- 1 to 10) {
            if (a == 5) {
               return // terminate the loop
            }
            println("Value of a: " + a)
         }
      }
      loopWithReturn()
   }
}

In above example, loop is placed inside a function. The return is used to exit the function. So effectively breaking the loop.

Save the above program in ReturnBreakDemo.scala. The following commands are used to compile and execute this program.

Command

\>scalac ReturnBreakDemo.scala
\>scala ReturnBreakDemo

Output

Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4

2. Using Boolean Flag

A boolean flag can be used to control the loop execution.

object BooleanFlagBreakDemo {
   def main(args: Array[String]) = {
      var shouldBreak = false

      for (a <- 1 to 10 if !shouldBreak) {
         if (a == 5) {
            shouldBreak = true // set flag to terminate the loop
         } else {
            println("Value of a: " + a)
         }
      }
   }
}

In above example, a boolean flag (shouldBreak) is used to control the loop execution. When the flag is set to true, the loop terminates.

Save the above program in BooleanFlagBreakDemo.scala. The following commands are used to compile and execute this program.

Command

\>scalac BooleanFlagBreakDemo.scala
\>scala BooleanFlagBreakDemo

Output

Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4

Using Higher-Order Functions

Scala collection library has higher-order functions like takeWhile to control loop execution.

object HigherOrderFunctionDemo {
   def main(args: Array[String]) = {
      (1 to 10).takeWhile(_ != 5).foreach(a => println("Value of a: " + a))
   }
}

The takeWhile function processes elements until the condition (_ != 5) is met. So terminates the loop when the condition is false.

Save the above program in HigherOrderFunction Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac HigherOrderFunctionDemo.scala
\>scala HigherOrderFunctionDemo

Output

Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
Advertisements