Article Directory
break 和 continue
- In the scala, like Java and C ++ break / continue keyword is removed
- If you must use break / continue, we need to use the class scala.util.control Break packages
breable
andbreak
methods.
Achieve break
- Import Breaks package
import scala.util.control.Breaks._
- The expression for use breakable wrap
- for expressions where needed to exit the loop, add the
break()
method call
The sample code
//使用for表达式打印1-100的数字,如果数字到达50,退出for表达式
// 导入scala.util.control包下的Break
import scala.util.control.Breaks._
breakable{
for(i <- 1 to 100) {
if(i >= 50) break()
else println(i)
}
}
Continue to achieve
continue with the implementation of similar break
with one difference:实现break是用breakable{}将整个for表达式包起来,而实现continue是用breakable{}将for表达式的循环体包含起来就可以了
The sample code
//打印1-100的数字,使用for表达式来遍历,如果数字能整除10,不打印
// 导入scala.util.control包下的Break
import scala.util.control.Breaks._
for(i <- 1 to 100 ) {
breakable{
if(i % 10 == 0) break()
else println(i)
}
}