Should I use var in Java 10? [closed]

混江龙づ霸主 提交于 2019-12-19 03:21:35

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!