When to use var in Java 10

Java 10 officially introduced the var keyword to declare the local variable without typing the type information. Java developers have needed to keep typing the class name explicitly for a long time.

var keyword allows us to declare the local variable without type information supported by the power of type inference of Java compiler. We can simplify the following code.

String str = "Hello, Java!"

like this

var str = "Hello, Java!"

But is it beneficial for practical use? Does it make the code better from the viewpoint of the readability and maintainability?

I have found an interesting discussion in the Presto community about the var usage. Let me summarize the point here.



Overall, the Presto community does not prefer using the var for now. That’s pretty reasonable. From my experience, the var usage did not improve the readability even though it could worsen it. Thanks to the power of IDE (e.g. IntelliJ IDEA), it would not be much trouble to type lengthy class name in Java anymore.

Therefore, we may need to be careful to use the var declaration in general. If we are sure to simplify the expression by eliminating the tiring generic type declaration (See 4th item in Pros), there might be room to use it.

I am also interested in how the other Java community treats the var usage in their project.