Skip to content

Commit 7bdd5c7

Browse files
committed
Refactor: Talk about boundary/break instead of scala.util.control.NonLocalReturns
Corrections
1 parent 32add3d commit 7bdd5c7

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

docs/_docs/reference/dropped-features/nonlocal-returns.md

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,18 @@ Returning from nested anonymous functions has been deprecated, and will produce
99

1010
Nonlocal returns are implemented by throwing and catching `scala.runtime.NonLocalReturnException`-s. This is rarely what is intended by the programmer. It can be problematic because of the hidden performance cost of throwing and catching exceptions. Furthermore, it is a leaky implementation: a catch-all exception handler can intercept a `NonLocalReturnException`.
1111

12-
A drop-in library replacement is provided in [`scala.util.control.NonLocalReturns`](https://scala-lang.org/api/3.x/scala/util/control/NonLocalReturns$.html). Example:
12+
A better alternative to nonlocal returns and also the `scala.util.control.Breaks` API is provided by [`scala.util.boundary` and `boundary.break`](http://dotty.epfl.ch/api/scala/util/boundary$.html).
13+
14+
Example:
1315

1416
```scala
15-
import scala.util.control.NonLocalReturns.*
16-
17-
extension [T](xs: List[T])
18-
def has(elem: T): Boolean = returning {
19-
for x <- xs do
20-
if x == elem then throwReturn(true)
21-
false
22-
}
23-
24-
@main def test(): Unit =
25-
val xs = List(1, 2, 3, 4, 5)
26-
assert(xs.has(2) == xs.contains(2))
17+
import scala.util.boundary, boundary.break
18+
19+
def firstIndex[T](xs: List[T], elem: T): Int =
20+
boundary:
21+
for (x, i) <- xs.zipWithIndex do
22+
if x == elem then break(i)
23+
-1
2724
```
2825

2926
Note: compiler produces deprecation error on nonlocal returns only with `-source:future` option.

0 commit comments

Comments
 (0)