Scala Tutorial Scala References

Scala - Break Statement



Scala supports break statement after importing util.control.Breaks package. The break statement in Scala is used to terminate the program out of a given breakable object whenever the condition is met.

Break statement with While loop

In the example below, break statement is used to get out of the while loop if the value of variable j becomes 4.

import util.control.Breaks._

object MainObject {
  def main(args: Array[String]) {
    var j = 0
    
    //creating a breakable loop
    breakable {
      while (j < 10){
        j += 1
        if(j == 4){
          println("Getting out of the loop.")
          break
        }
        println(j) 
      }      
    }
  }
}

The output of the above code will be:

1
2
3
Getting out of the loop.

Using Break statement like Continue statement

By placing the breakable objects carefully in the loop, a break statement can be used like a continue statement (like in C++ or Java). In the example below, break statement is used to skip the while loop if the value of variable j becomes 4.

import util.control.Breaks._

object MainObject {
  def main(args: Array[String]) {
    var j = 0
    
    while (j < 10){
      //creating a breakable loop
      breakable {
        j += 1
        if(j == 4){
          println("this iteration is skipped.")
          break
        }
        println(j) 
      }      
    }
  }
}

The output of the above code will be:

1
2
3
this iteration is skipped.
5
6
7
8
9
10

Naming a breakable object

In Scala, it is possible to assign a name to a breakable object. It can be done after importing util.control package. This feature is quite useful when working with number of breakable objects. Consider the example below:

import util.control._

object MainObject {
  def main(args: Array[String]) {
    
    //creating a breakable loop
    val MyLoop = new Breaks

    MyLoop.breakable{
      for (i <- 1 to 10) {
        if(i == 4){
          println("Getting out of the loop.")
          MyLoop.break
        }
        println(i) 
      }      
    }
  }
}

The output of the above code will be:

1
2
3
Getting out of the loop.