How to quickly de-lombok a val in IntelliJ IDEA
Many of my projects are still on Java 8, and I use Lombok extensively. I especially like the
val keyword which is similar to Java 11’s local variable type inference, which is otherwise inaccessible in Java 8. Instead of saying:
String string = "example";
with Lombok, I often say:
val string = "example";
This may not save too many keystrokes in this case, but if the class names get long,
val can really simplify the code. Unfortunately, sometimes it gets in your way, and you want to revert it to the old ways.
Even if you have the lombok plugin in IntelliJ IDEA, that supports de-lomboking of annotations, there’s no quick way to de-lombok the
val keyword. So this is the easiest way I could find to do it — in just 4 keystrokes.
Suppose you have this line and you want to replace
val with the actual variable type —
String in this case. (Once again, in this case it’s easier to just write
String instead of
val, but imagine the expression is much more complicated, and the type name is lengthy.)
Now you put your cursor on the beginning of the
string variable name and hit Alt+Backspace (or Option+Backspace, for Mac users) to remove the
IDEA can’t compile the code and proposes some quick fixes for you with this red lightbulb on the left hand side. To invoke this quick fixes menu, press Alt+Enter (Option+Enter):
The first option is what we want — it transforms the invalid expression into a local variable:
The only thing we need to do now is to select the variable type, and in most of the cases, this would be the first one, inferred by IDEA, so we just hit Enter:
So now we have a de-lomboked compiling code in only 4 keystrokes: Alt+Backspace, Alt+Enter, Enter, Enter.