tags:

views:

309

answers:

3

Is there any real reason of providing the return statement in Scala? (aside from being more "Java-friendly")

+10  A: 

It is provided in order to accommodate those circumstances in which it is difficult or cumbersome to arrange all control flow paths to converge at the lexical end of the method.

While it is certainly true, as Dave Griffith says, that you can eliminate any use of return, it can often be more obfuscatory to do so than to simply cut execution short with an overt return.

Be aware, too, that return returns from methods, not function (literals) that may be defined within a method.

Randall Schulz
I knew that was the answer.. I just can't think of any examples.
Jus12
Fortunately for me, you didn't ask for any examples...
Randall Schulz
+7  A: 

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
}
Dave Griffith
Thanks for the answer. This is very informative.
Jus12
I think this is a more formal answer. I am interested in the proof of the result you mention. Can you provide some references?
Jus12
Added a link to wikipedia for the structured program theorem.
Dave Griffith
+1  A: 

I view return as a useful when writing imperative style code, which generally means I/O code. If you're doing pure functional code, you don't need (and should not use) return. But with functional code you may need laziness to get performance equivalent to imperative code that can "escape early" using return.

Lachlan