English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Scala does not have a default break statement, but you can use Scala 2.8 version, you can use another method to achieve this break statement. When using break A statement that, when executed, will break out of the loop and execute the code block following the loop body.
The syntax for break in Scala is a bit different, as follows:
// Import the following packages import scala.util.control._ // Create a Breaks object val loop = new Breaks; // Looping within breakable loop.breakable{ // Loop for(...){ .... // Loop Break loop.break; } }
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 above code is as follows:
$ scalac Test.scala $ scala Test Value of a: 1 Value of a: 2 Value of a: 3 Value of a: 4 After the loop
The following example demonstrates how to break 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; } } } // Break of the nested loop } } // Break of the external loop } }
The output of the above code is as follows:
$ 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