Scala 中如何使用 continue 和 break 跳出循环
示例代码:
object Test {
def main(args: Array[String]): Unit = {
import scala.util.control.Breaks._
println("=============== Continue ===================")
for (i <- 1 to 10) {
breakable {
if (i % 2 == 0) {
break
}
println(i)
}
}
println("=============== Continue ===================")
for (i <- 1 to 10 if i % 2 != 0) {
println(i)
}
println("=============== Break ===================")
breakable {
for (i <- 1 to 10) {
if (i % 2 == 0) {
break
}
println(i)
}
}
println("=============== Break ===================")
var loop = true
for (i <- 1 to 10 if loop == true) {
if( i % 2 == 0){
loop = false
}
println(i)
}
}
}
查看Breaks源码得知,breakable 与 break 方法组合用于控制循环的原理就是利用 break 方法抛出一个异常,然后 breakable 方法再捕获这个异常,从而结束整个 breakable 方法块内代码的执行,但是不影响 breakable 方法体外代码的执行,从而实现控制。
源码如下:
package scala
package util.control
/** A class that can be instantiated for the break control abstraction.
* Example usage:
* {
{
{
* val mybreaks = new Breaks
* import mybreaks.{break, breakable}
*
* breakable {
* for (...) {
* if (...) break()
* }
* }
* }}}
* Calls to break from one instantiation of `Breaks` will never
* target breakable objects of some other instantiation.
*/
class Breaks {
private val breakException = new BreakControl
/**
* A block from which one can exit with a `break`. The `break` may be
* executed further down in the call stack provided that it is called on the
* exact same instance of `Breaks`.
*/
def breakable(op: => Unit) {
try {
op
} catch {
case ex: BreakControl =>
if (ex ne breakException) throw ex
}
}
sealed trait TryBlock[T] {
def catchBreak(onBreak: =>T): T
}
/**
* This variant enables the execution of a code block in case of a `break()`:
* {
{
{
* tryBreakable {
* for (...) {
* if (...) break()
* }
* } catchBreak {
* doCleanup()
* }
* }}}
*/
def tryBreakable[T](op: =>T) = new TryBlock[T] {
def catchBreak(onBreak: =>T) = try {
op
} catch {
case ex: BreakControl =>
if (ex ne breakException) throw ex
onBreak
}
}
/**
* Break from dynamically closest enclosing breakable block using this exact
* `Breaks` instance.
*
* @note This might be different than the statically closest enclosing block!
*/
def break(): Nothing = { throw breakException }
}
/** An object that can be used for the break control abstraction.
* Example usage:
* {
{
{
* import Breaks.{break, breakable}
*
* breakable {
* for (...) {
* if (...) break
* }
* }
* }}}
*/
object Breaks extends Breaks
private class BreakControl extends ControlThrowable
还没有评论,来说两句吧...