What is the meaning of this?
Neal Gafter
neal at gafter.com
Thu Jan 28 14:38:10 PST 2010
> On 28 Jan 2010, at 21:46, Peter Levart wrote:
>> Local variables are perfectly thread-safe:
>>
>> void method()
>> {
>> final #int(int) factorial = #(int i)(i == 0 ? 1 : i * factorial.(i - 1));
>> }
>>
>> This can be made allowed, since evaluation of lambda expression is not using the value of final
>> variable being defined, it's just capturing it and there are no recursive type resolving problems
>> here.
On Thu, Jan 28, 2010 at 2:07 PM, Mark Mahieu <markmahieu at googlemail.com> wrote:
> Yep, that's how I used to do it with BGGA for example. It seemed obvious enough at the time that I never even considered 'stashing it in a field'.
Yes. It requires a special mention in the specification (otherwise
the variable "factorial" in the lambda isn't definitely assigned), but
that is worth doing.
> I guess that wouldn't work when using a self-referencing lambda as an argument to a super-constructor call. Still, that's not a problem specific to lambdas, and the possible 'solutions' (which might include let-expressions) probably have wider applicability too.
Well, yes. But until then we already have a solution for those rare
occasions when the simple solutions don't work. Just use an anonymous
inner class. You can even combine this solution with a lambda if you
must:
// recursive factorial lambda
#int (int n) (new Object(){
int fac(int n) { return n<=1 ? n : n*fac(n-1); }
}.fac(n))
Better yet, just promote the darn thing to a method:
// recursive factorial
private static int fac(int n) { return n<=1 ? n : n*fac(n-1); }
// factorial lambda
#int(int n) ( fac(n) )
The need for this kind of thing is much less frequent than the need to
refer to things in the enclosing scope, and the demonstrably confusing
scoping rules of inner classes* are best avoided in new language
constructs like lambda expressions, as they have been avoided in every
other object-oriented language with lambdas.
Cheers,
Neal
* Some discussion of the confusion caused by the scoping in anonymous
inner classes can be found here
http://blogs.sun.com/jrose/entry/scope_ambiguities_between_outer_and
http://dyla2007.unibe.ch/?download=dyla07-Gilad.pdf
http://www.javapuzzlers.com/ e.g. puzzle 92
More information about the lambda-dev
mailing list