Quick Coding Tip: Why Wait for JDK 10?

DZone 's Guide to

Quick Coding Tip: Why Wait for JDK 10?

Take a look at the somewhat complicated relationship between Lombok and JDK 10. While it's boon to reduce boilerplate code, Lombok and Java 10's var can fill a couple of the same gaps.

· Java Zone ·
Free Resource

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 and 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?

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.

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!

Useful Links

java, local variable type inference, lombok, tutorial, val, var

Published at DZone with permission of Mark Heckler , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}