在 GitHub 上編輯此頁面

已棄用:非區域回傳

自 Scala 3.2.0 起,已棄用從巢狀匿名函式回傳。

非區域回傳是透過拋出並捕捉 scala.runtime.NonLocalReturnException-s 實作的。這很少是程式設計師的本意。由於拋出和捕捉例外狀況的效能成本隱藏,這可能會造成問題。此外,這是一個有缺陷的實作:全域例外狀況處理常式可以攔截 NonLocalReturnException

非區域回傳和 scala.util.control.Breaks API 的更佳替代方案是 scala.util.boundaryboundary.break 提供的。

範例

import scala.util.boundary, boundary.break
def firstIndex[T](xs: List[T], elem: T): Int =
  boundary:
    for (x, i) <- xs.zipWithIndex do
      if x == elem then break(i)
    -1