New

Neal Gafter neal at gafter.com
Mon Mar 29 09:14:06 PDT 2010


On Mon, Mar 29, 2010 at 5:36 AM, Howard Lovatt <howard.lovatt at gmail.com>wrote:

> A number of people have commented about using new for lambdas, there are at
> least 4 good reasons to use new:
>
> 1. It is what the rest of Java uses, e.g.:
>
>  List<Integer> list = new ArrayList<Integer>();
>  #<int()> lambda = new #<int()>(42);
>

Only for object creation.  A lambda expression is not a mechanism for
creating an object, so being consistent in this area would be a
disadvantage.


> 2. It is compatible with the diamond operator from Coin (assuming <> are
> used), e.g.:
>
>  List<Integer> list = new ArrayList<>();
>  #<int()> lambda = new #<>(42);
>

Given that they have nothing whatsoever to do with each other, that's a
disadvantage too.


> 3. The main argument for not using new is that the compiler can 'lift' the
> lambda to be static if it doesn't access any instance fields or local
> variables. However this type of optimization has a poor history in Java,...
>

This isn't an optimization.  The compiler needs to translate each lambda
expression into a reference to a suitable object, and select an appropriate
lifetime for that object.  The compiler should not intentionally generate
bad code in the hope that it will be improved later.

... Note how control over creation is critical, multiple frameClicked()
> calls
> can be safely eliminated but multiple fileMenuClicked() calls cannot
> because
> these toggle the menu.
>

Actually, in your example control over creation (of the function object) is
not at all critical, because the creation time is not visible to the
program.  I agree that multiple fileMenuClicked() calls cannot be
eliminated; that is because it has a side-effect "jobs.put(toggleFileMenu);"
having nothing at all to do with lambda creation.  The (hidden) creation
time of the function object designated by the lambda has no impact on the
program's semantics.


More information about the lambda-dev mailing list