Scala 中没有 break(2.8 中将会支持) 和 continue,的确是件纠结的事情啊~
更纠结的是,return 似乎也不能直接 work
比如 Java 里头可以这样写(虽然这样写并不好):
但是 Scala 里头怎么办列,或许换种思考的方式会更好:
对于 break 和 continue,
更纠结的是,return 似乎也不能直接 work
比如 Java 里头可以这样写(虽然这样写并不好):
for(int i = 0; i < 10; i++){
System.out.println("i = " + i);
if(i == 1){
System.out.println("return at i = 1");
return;
}else if( i == 2){
System.out.println("return i = 2");
return ;
}
}
但是 Scala 里头怎么办列,或许换种思考的方式会更好:
(0 until 10).find{ i => println("i = " + i) i match { case 1 => println("return at i = 1"); true case 2 => println("return at i = 2"); true case _ => false }}
对于 break 和 continue,
引用
These keywords are not included in Scala 2.7, and must be implemented in a different way. For break, the simplest thing to do is to divide your code into smaller methods and use the return to exit early. For continue, a simple approach is to place the skipped-over parts of a loop into an if.
Scala 2.8 will include break, but not continue.
Scala 2.8 will include break, but not continue.