scala中怎麼跳出循環

在java中跳出循環的時候,我們可以直接break就行了,但是在scala裏面沒有break,那怎麼跳出循環呢?

直接看下面的demo:

package test

import scala.util.control.Breaks

object ListDemo {
  def main(args: Array[String]): Unit = {
    var loop = Breaks
    var i = 0
    loop.breakable {
      while (i < 10) {
        println(i)
        i += 1
        if (i == 5) {
          loop.break()
        }
      }
    }
  }
}

這個地方需要用loop.breakable包括一下,不然會報一個錯

Exception in thread "main" scala.util.control.BreakControl

下面看一下Breaks的源碼:

/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2013, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

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

從上面的源碼可以看出,breakable與break方法組合用於控制循環的原理就是利用break方法拋出一個異常,然後breakable方法再捕獲這個異常,從而結束整個breakable方法塊內代碼的執行,但是不影響breakable方法體外代碼的執行,從而實現控制。

如果有寫的不對的地方,歡迎大家指正,如果有什麼疑問,可以加QQ羣:340297350 謝謝

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章