New
Howard Lovatt
howard.lovatt at gmail.com
Mon Mar 29 02:36:45 PDT 2010
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);
2. It is compatible with the diamond operator from Coin (assuming <> are
used), e.g.:
List<Integer> list = new ArrayList<>();
#<int()> lambda = new #<>(42);
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,
think String interning and copying of static fields. In Java a JVM
optimization has proven much more successful than a compiler optimization.
Hence using new, which would allow a JVM optimization but prevent a compiler
optimization, is the best choice.
4. There are times when you want to control instantiation, consider a GUI
application that uses a custom queue that checks for double entries (e.g.
caused by an impatient user multiply single clicking - I do this!), the job
queue might be:
class Jobs extends LinkedBlockingDeque< #<void()> > {
@Override public void put( final #<void()> e ) {
if ( !peekLast().equals( e ) ) { super.put( e ); }
}
}
Then you might implement the main class of an application as:
class GUI {
private static final Jobs jobs = new Jobs();
private static final #<int()> FRAME_TO_FRONT = new #<> { ... };
static void frameClicked() { jobs.put( FRAME_TO_FRONT ); }
static void fileMenuClicked() {
final #<void()> toggleFileMenu = new #<> { ... };
jobs.put( toggleFileMenu );
}
...
}
Note how control over creation is critical, multiple frameClicked() calls
can be safely eliminated but multiple fileMenuClicked() calls cannot because
these toggle the menu.
-- Howard.
PS # could be substituted for lambda, Lambda, Function, etc.
More information about the lambda-dev
mailing list