Home » Scala language

break statement in Scala

In Scala, the loop execution can be terminated at any point using the break statement. In this tutorial, we will learn how to use break is Scala, its usage, syntax, and examples?
Submitted by Shivang Yadav, on June 22, 2019

break statement in Scala

The break statements are used to terminate the execution of the code block at any point in the block. Loops are not different than a code block. In Scala, there is no break keyword, it was removed from Scala after the release of 2.8 Version. From this version, the break keyword was replaced by the break method that is used in Scala in place of break keyword to terminate Scala loops.

The break method needs to be imported, this can be done by using the following import statement, import scala.util.control.break.

The break statement can be used to terminate all type of loop statements like, for, while, do-while and nested loops.

First to import break keyword: import scala.util.control.Breaks._

This statement imports the breaks class that contains the break method.

Syntax to use:

    var loop = new breaks;
			    //code to be executed
			    Loop. break;


First, the loop object is created that is used to use all the methods of the class. The breakable method is used to handle any exceptions that may come while breaking a statement. The loop inside it is executed as it is and when the break method is encountered the loop is terminated and the program goes out of the loop code.

Example code:

import scala.util.control._
object MyClass {
      def main(args: Array[String]) {
         var loop = new Breaks;
         var i = 0
             for(i <-  2 until 10){
                 if(i == 5){



Code explanation:

First, we have imported the control package that contains breaks class that contains the break method. This break method is used by making an object of the breaks class. the loop is the object of the breaks class that is used to call breakable and break. The breakable is used to handle all the errors that may occur by the break method call. Then the break method is used to terminate the loop statement.

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.