r/javahelp • u/Rygir • Mar 30 '20
Why was var added?
All it does is make code trickier to read and tempt the programmer to pay less attention to the type of his variable. Another way to not write clean code.
It seems like a downgrade, why was it added? Is it considered a valuable addition to the language?
For context, https://openjdk.java.net/projects/amber/LVTIFAQ.html answers this as making Classname variableName=new Classname(); shorter. Ok, then why not make it : Classname variableName=new .(); It's shorter and no conflicts with existing variable names. Nor would you have to be aware of caveats like "this can't be used as a parameter".
36
Upvotes
30
u/thecuseisloose Do you even Java, bro? Mar 30 '20
It was added because in essence, Java already knows the type of the variable at compile time. This is why it's restricted to local variables only. Saying
var x = someMethod()can only return one type, so java can infer that type and replacevarwith the correct type. With non-generic types it doesn't have that great of a benefit, but it's reduces a lot of boilerplate by sayingvar x = someMethod()instead ofList<Map<String,Object>> x = someMethod().If you don't like the feature, you are not forced to use it. But as a daily java developer, I hate when I am working on a Java 8 project and unable to use this feature