Quick coding tip: Why wait for JDK 10?

Lombok is one of those libraries that plugs several small gaps in fairly basic Java functionality. It covers so many small gaps, in fact, that it's easy to use it to provide some very useful capabilities for years while overlooking other capabilities it quietly provides just as well.

This happened to me recently, as I mentioned in the tweet below. Caveat: I'm for code clarity first and foremost, so I don't recommend sacrificing readability...but if there is a way to be more concise, i.e. stating/coding something with less text while retaining full context, I'm for it.

Enter JDK 10's var option for declaring local variables, courtesy of Project Amber & JEP 286. If you're not using Kotlin (or Groovy, Scala, Javascript, etc.) in your shop, this small detail may hold some appeal for you. But it's (to date) only available in JDK 10...are you and your team using JDK 10 yet? Chances are, you aren't. Ah, but what about Lombok?

val & var in Lombok

Ignoring all the other things it can do, Lombok also enables you to declare local variables as values (immutable) and variables (mutable). Here's how:

To declare local immutable values, just use the val "keyword" (actually a Lombok type of sorts) where you would normally provide the type declaration. Lombok's var works similarly, except it creates a mutable type.

@Data
@AllArgsConstructor
class MyClass {  
    public void logIt() {
        val logMessage = "This is my sweet log message";
        var logStatus = 909;

        System.out.println("Log status: " + logStatus + ", message: " + logMessage);
    }
}

The relevant import statements will likely be suggested by your IDE, but here they are for reference:

import lombok.experimental.var;  
import lombok.val;  

The first time you try to compile your class using var, you'll see this error message:

Error:(37, 13) java: Use of var is disabled by default. Please add 'lombok.var.flagUsage = ALLOW' to 'lombok.config' if you want to enable is.  

This is easily resolved by creating a file called lombok.config in your project's root and adding the single entry lombok.var.flagUsage = ALLOW, as recommended. Subsequent builds should perform as expected.

Click here to follow me on Twitter for more quick tips like this. Happy coding!

Lombok features JEP 286