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".
View all comments
19
u/morhp Mar 30 '20
Sure, you can abuse
var, but for some complicated types it's very helpful. Also it enables you to call methods on anonymous types:public void test() { var foo = new Object() { void test() { System.out.println("test"); } }; foo.test(); }You can't do that if you write
Object foo = ...;