return-from-lambda viewed as dangerous, good alternatives
Alex Blewitt
alex.blewitt at gmail.com
Thu Jan 7 01:38:02 PST 2010
On Jan 7, 2010, at 09:16, John Rose wrote:
> On Dec 28, 2009, at 8:25 AM, Neal Gafter wrote:
>
>> To: Peter Levart <peter.levart at gmail.com>
>> Cc: lambda-dev at openjdk.java.net
>> Subject: Re: transparent lambda
>>
>> I'm moving this conversation to the closures-dev mailing list.
>
> I note that the closures-dev group is dealing with the details of
> what fully transparent lambdas would look like, and in particular
> how to avoid overloading "return".
>
> First, if we were going to do "transparent lambdas" (which I
> understand we're not, but stay with me a second), adding a new
> meaning to the "return" keyword obviously interferes with the old
> meaning, which is "find the enclosing method and return a value from
> it". You can test this interference by imagining a hapless
> programmer refactoring code and pasting some stuff containing a
> "return" statement into a new lambda expression.
I find this a pretty banal argument. 'We shouldn't do this because of
copy and paste errors'? Seriously? What kind of refactoring is copy
and paste?
Exactly the same thing happens when you select a block of code in an
IDE (like Eclipse) and say 'make into method'. That checks to see if
there's any returns in the block code, which would otherwise be
invalid, and issues an appropriate warning. It can even, in some
cases, detect that there's only one return and then promote a return
outside the expression before evaluating.
Furthermore, it's no different if someone was dealing with code
looking like:
public class Outer {
public Runnable foo(double level) {
return new Runnable() {
public void run() {
while(true) {
if (Math.random() > level)
return; // Return from Runnable, not Outer#foo
System.out.println("looping");
}
}
}
}
Every Java developer will know that the 'return' here applies to the
'run' method and not the 'foo' that is instantiating the inner class.
Why should it be any different if the code was extracted into a lambda
instead of a Runnable, especially if SAM promotion occurs?
What should be absolutely disallowed is any kind of concept that
break, continue, or return has any concept outside the lambda. In
other words, a return inside a lambda should definitely not be
something that can control the flow to the body that instantiated it,
since that's not the same time when it gets executed. So the
definition of 'return' needs to be changed to 'enclosing method or
lambda', and not by preventing it from being inside a lambda on
principle.
Alex
More information about the lambda-dev
mailing list