How far to go in replacing inner classes with lambdas?
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Mon Oct 29 02:54:48 PDT 2012
On 28/10/12 16:12, Brian Goetz wrote:
> The IntelliJ EAP builds already have inspections for "replace inner
> with lambda" and "replace lambda with method reference" (nice job, guys!)
Note that javac has been supporting a similar suggestion from early
days: it detect inner classes that are lambdifiable when the
-XDidentifyLambdaCandidates is enabled. I think at some point I even did
an experiment to see how many instances I could find in the JDK - some
snippets are reported below:
*) Total SAM types in JDK: 807
*) Total potential lambda sites in JDK: 1862
[It is possible that the above numbers are a bit different now, because
of changes in the nature of the functional interface definition and
changes to the JDK codebase - however they should give a rough idea of
how many potential lambda sites we have in our code].
Maurizio
>
> 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