Scala break 語句

Scala 循環(huán)

Scala 語言中默認(rèn)是沒有 break 語句,但是你在 Scala 2.8 版本后可以使用另外一種方式來實(shí)現(xiàn) break 語句。當(dāng)在循環(huán)中使用 break 語句,在執(zhí)行到該語句時,就會中斷循環(huán)并執(zhí)行循環(huán)體之后的代碼塊。

語法

Scala 中 break 的語法有點(diǎn)不大一樣,格式如下:

// 導(dǎo)入以下包
import scala.util.control._
// 創(chuàng)建 Breaks 對象
val loop = new Breaks;
// 在 breakable 中循環(huán)
loop.breakable{
    // 循環(huán)
    for(...){
       ....
       // 循環(huán)中斷
       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" );
   }
}

執(zhí)行以上代碼輸出結(jié)果為:

$ scalac Test.scala
$ scala Test
Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
After the loop

中斷嵌套循環(huán)

以下示例演示了如何中斷嵌套循環(huán):

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;
                  }
               }
            } // 內(nèi)嵌循環(huán)中斷
         }
      } // 外部循環(huán)中斷
   }
}

執(zhí)行以上代碼輸出結(jié)果為:

$ 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 循環(huán)

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清