Refactoring lambdas

Somehow I quite often starter with a lambda that has a single statement, like:

   Supplier<String> c = ()-> "".substring(0);

However, then sometime later I need to convert this into a block because I need more than one statement.

   Supplier<String> c = ()-> { 
        return "".substring(0);
    };

I you use command-1 when the cursor is inside the statement, for example on the substring, you do not get an option to convert the single statement to a block.
image

However, I just found out that if you put the cursor on the arrow of the lambda, you get lots of options, also the option to convert a single line lambda to a block!

This seems to be true for many other refactorings of lambdas. I looked many times for a refactoring that would change something like s -> s.length() to String::length and it actually exists as long as the cursor is on the arrow.

Maybe the whole world knows this and I am the last. But found it very useful.

2 Likes

Thanks for sharing this. Yeah I also often go crazy putting the cursor in different kinds of places and press Cmd + 1 just to see which refactorings I am offered. I it even sometimes it works with selecting a block of text - but not completely sure.
E.g. I there is a way to convert an if - else if - else into a switch statement… and if you switch on an enum you can automatically create a switch on all the missing names of this enum.
A lot seems to be there.

I never googled this before but I now found this:

2 Likes

That help page is really useful.

I am working on this for bndtools at the moment for OSGi specific stuff, will be mindblowing … :wink: