Work in Progress

We are still in the process of writing the documentation for Scala 3. You can help us to improve the documentation.

Are you searching for the Scala 2 documentation?

Scala 3 Language Reference

Deprecated: Nonlocal Returns


Returning from nested anonymous functions has been deprecated.

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.

A drop-in library replacement is provided in scala.util.control.NonLocalReturns. Example:

import scala.util.control.NonLocalReturns.*

extension [T](xs: List[T])
  def has(elem: T): Boolean = returning {
    for x <- xs do
      if x == elem then throwReturn(true)

@main def test(): Unit =
  val xs = List(1, 2, 3, 4, 5)
  assert(xs.has(2) == xs.contains(2))

Contributors to this page: