问题
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();
回答1:
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.
来源:https://stackoverflow.com/questions/50040439/should-i-use-var-in-java-10