Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use var in Java 10? [closed]

Tags:

java

java-10

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();
like image 477
Antho Christen Avatar asked Apr 26 '18 10:04

Antho Christen


1 Answers

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.

like image 179
Impulse The Fox Avatar answered Oct 26 '22 03:10

Impulse The Fox