Scala学习笔记(三)
Scala break语句
在Scala中可以没有内置break语句,但如果正在运行的Scala2.8,那么还有一个办法使用break语句。当break语句在循环中遇到循环立即终止,程序控制继续下一个循环语句后面的。
语法:
break语句的语法是有点不同寻常,但它的工作原理:
// import following package
import scala.util.control._
// create a Breaks object as follows
val loop = new Breaks;
// Keep the loop inside breakable as follows
loop.breakable{
// Loop will go here
for(...){
....
// Break will go here
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" );
}
}
当上述代码被编译和执行时,它产生了以下结果:
C:/>scalac Test.scala
C:/>scala Test
Value of a: 1
Value of a: 2
Value of a: 3
Value of a: 4
After the loop
打断嵌套循环:
使用嵌套循环打破现有循环。所以,如果有使用break嵌套循环,那么下面的方式来进行:
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;
}
}
} // inner breakable
}
} // outer breakable.
}
}
注意打断循环嵌套这里:
breakable只能打断他自己包含的循环,例如上例里面的inner breakable打断了自己的循环却没有打断outer breakable循环,如果在outer breakable再设定break的话这样才能打断outer breakable(注意添加条件)