Should I use var in Java 10?

Antho Christen picture Antho Christen · Apr 26, 2018 · Viewed 8.2k times · Source

Given that I can't use var for non-denotable types(Nulls, Anonymous Classes, Some Single Method Class and most importantly Intersecting Types). Am I better off not using it for better readability and consistency (given that its only for local types)?

I kind of feel that it would be abused,

var a = someObj.getSomeValue().getSomethingElse().returnsSomething();

Answer

Impulse The Fox picture Impulse The Fox · Apr 26, 2018

Though this is probably primarily opinion-based, I'd say: No, it is not evil.

The var keyword is only allowed when the type of the variable is already clear at compile-time. Also, it will generate the same bytecode, so there is nothing to fear.

In some cases like null, var is not allowed. This doesn't make it evil, but rather good. If this was not the case, Java would not be statically typed anymore. (Note, however, it is allowed in most of the cases you've listed.)

Also I don't see any problem with your example. Since your .returnsSomething() would rather be something like .getPerson() in the real world, it would be clear to the reader that var is a Person.