×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

break statement in Scala

By IncludeHelp Last updated : October 10, 2024

Break statement

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 statement can be used to terminate all type of loop statements like, for, while, do-while and nested loops.

Import statement

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

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

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

Syntax to use

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.

var loop = new breaks;
loop.breakable{
  {
    loop(){
      //code to be executed
      Loop. break;
    }
  }
}

Example of break statement

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

Output

2
3
4
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.