Purpose of “return” statement in Scala?

Ignoring nested functions, it is always possible to replace Scala calculations with returns with equivalent calculations without returns. This result goes back to the early days of “structured programming”, and is called the structured program theorem, cleverly enough.

With nested functions, the situation changes. Scala allows you to place a “return” buried deep inside series of nested functions. When the return is executed, control jumps out of all of the nested functions, into the the innermost containing method, from which it returns (assuming the method is actually still executing, otherwise an exception is thrown). This sort of stack-unwinding could be done with exceptions, but can’t be done via a mechanical restructuring of the computation (as is possible without nested functions).

The most common reason you actually would want to return from inside a nested function is to break out of an imperative for-comprehension or resource control block. (The body of an imperative for-comprehension gets translated to a nested function, even though it looks just like a statement.)

for(i<- 1 to bezillion; j <- i to bezillion+6){
if(expensiveCalculation(i, j)){
   return otherExpensiveCalculation(i, j)
}

withExpensiveResource(urlForExpensiveResource){ resource =>
// do a bunch of stuff
if(done) return
//do a bunch of other stuff
if(reallyDoneThisTime) return
//final batch of stuff
}

Leave a Comment