- 12.1 Functions as Values
- 12.2 Anonymous Functions
- 12.3 Parameters That Are Functions
- 12.4 Parameter Inference
- 12.5 Useful Higher-Order Functions
- 12.6 Closures
- 12.7 Interoperability with Lambda Expressions
- 12.8 Currying
- 12.9 Methods for Composing, Currying, and Tupling
- 12.10 Control Abstractions
- 12.11 Nonlocal Returns
- Exercises
12.11 Nonlocal Returns
In Scala, you don’t use a return statement to return function values. The return value of a function is simply the value of the function body.
A return statement would be particularly problematic with control abstractions. For example, consider this function:
def indexOf(str: String, ch: Char): Int = var i = 0 until (i == str.length) { if str(i) == ch then return i // No longer valid in Scala i += 1 } -1
Does return return from the anonymous function { if str(i) == ch then return i; i += 1 } that is passed to until, or from the indexOf function? Here, we want the latter. Earlier versions of Scala had a return expression that threw an exception to the enclosing named function. That fragile mechanism has been replaced with the returning control abstraction:
import scala.util.control.NonLocalReturns.* def indexOf(str: String, ch: Char): Int = returning { var i = 0 until (i == str.length) { if str(i) == ch then throwReturn(i) i += 1 } -1 }