Scala 語(yǔ)言中默認(rèn)是沒(méi)有 break 語(yǔ)句,但是你在 Scala 2.8 版本后可以使用另外一種方式來(lái)實(shí)現(xiàn) break 語(yǔ)句。當(dāng)在循環(huán)中使用 break 語(yǔ)句,在執(zhí)行到該語(yǔ)句時(shí),就會(huì)中斷循環(huán)并執(zhí)行循環(huán)體之后的代碼塊。
Scala 中 break 的語(yǔ)法有點(diǎn)不大一樣,格式如下:
// 導(dǎo)入以下包
import scala.util.control._
// 創(chuàng)建 Breaks 對(duì)象
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):
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