Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala break Statement

Scala break Statement

Scala loop Scala Loops

Scala has no break statement by default, but since Scala 2.8 you can use an alternative way to implement a break break statement. When used inside a loop, the break break statement, when execution reaches it, interrupts the loop and executes the code block after the loop body.

Syntax

The syntax of break in Scala is a bit different, in the following format:



// Import the following packages

import scala.util.control._



// Create Breaks object

val loop = new Breaks;



// Loop in breakable

loop.breakable{

    // 循环

    for(...){

       ....

       // Loop interruption

       loop.break;

   }

}

Flowchart

Example



import scala.util.control._



object Test {

   def main(args: Array[String]) {

      var a = 0;

      val numList = List(1,2,3,4,5,6,7,8,9,10);



      val loop = new Breaks;

      loop.breakable {

         for( a <- numList){

            println( "Value of a: " + a );

            if( a == 4 ){

               loop.break;

            }

         }

      }

      println( "After the loop" );

   }

}

The output of the code above is:



$ scalac Test.scala

$ scala Test

Value of a: 1

Value of a: 2

Value of a: 3

Value of a: 4

After the loop


Breaking Out of Nested Loops

The following example demonstrates how to break out of nested loops:



import scala.util.control._



object Test {

   def main(args: Array[String]) {

      var a = 0;

      var b = 0;

      val numList1 = List(1,2,3,4,5);

      val numList2 = List(11,12,13);



      val outer = new Breaks;

      val inner = new Breaks;



      outer.breakable {

         for( a <- numList1){

            println( "Value of a: " + a );

            inner.breakable {

               for( b <- numList2){

                  println( "Value of b: " + b );

                  if( b == 12 ){

                     inner.break;

                  }

               }

            } // 内嵌循环中断

         }

      } // 外部循环中断

   }

}

The output of the code above is:



$ scalac Test.scala

$ scala Test

Value of a: 1

Value of b: 11

Value of b: 12

Value of a: 2

Value of b: 11

Value of b: 12

Value of a: 3

Value of b: 11

Value of b: 12

Value of a: 4

Value of b: 11

Value of b: 12

Value of a: 5

Value of b: 11

Value of b: 12

Scala loop Scala Loops