How far to go in replacing inner classes with lambdas?

Brian Goetz brian.goetz at oracle.com
Sun Oct 28 09:12:13 PDT 2012


The IntelliJ EAP builds already have inspections for "replace inner with 
lambda" and "replace lambda with method reference" (nice job, guys!)

In browsing through the inspection results in the JDK, we find ourselves 
in the same position we did with Coin features like Diamond; many code 
snippets can be simplified, but not all code snippets that can be 
simplified should be.

Here's an example:

     private final static Executor defaultExecutor = new Executor() {
             // DirectExecutor using caller thread
             public void execute(Runnable r) {
                 r.run();
             }
         };

We could simplify this to:

     private final static Executor defaultExecutor = r -> r.run();

or further to

     private final static Executor defaultExecutor = Runnable::run;

(Executor is a SAM interface with one method, execute(Runnable).)


What guidelines can we offer users on when they should and should not 
replace inner classes with lambdas or method reference?  Does this last 
one look a little weird only because the powerful "unbound method 
reference" construct is still a little unfamiliar?


More information about the lambda-libs-spec-experts mailing list