Skip to content

Commit 5425919

Browse files
authored
Refactor: Redirection to boundary/break instead of scala.util.control.NonLocalReturns (#17583)
<img width="477" alt="Screenshot 2023-05-25 at 14 31 01" src="https://github.com/lampepfl/dotty/assets/44496264/37d0aeaf-7198-44e4-8cd8-af9cb06827c1"> Fixes: #17572
2 parents ee62f32 + 3502cef commit 5425919

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

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

+9-13
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,17 @@ 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).
1313

14-
```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-
}
14+
Example:
2315

24-
@main def test(): Unit =
25-
val xs = List(1, 2, 3, 4, 5)
26-
assert(xs.has(2) == xs.contains(2))
16+
```scala
17+
import scala.util.boundary, boundary.break
18+
def firstIndex[T](xs: List[T], elem: T): Int =
19+
boundary:
20+
for (x, i) <- xs.zipWithIndex do
21+
if x == elem then break(i)
22+
-1
2723
```
2824

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

0 commit comments

Comments
 (0)