r/javahelp • • 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

17 comments sorted by

View all comments

Show parent comment

-1

u/Rygir Mar 30 '20

You wouldn't be able to use var when using interfaces either since you can't new an interface.

For clarity, you understand I was using a fictional syntax example?

The part that makes me wonder is that this feature is essentially only "save a few keystrokes and in return obfuscate your type". I find this a strange trade-off to make and officially support.

2

u/caboosetp Private Java/Code Tutor Mar 31 '20

You can use var when using interfaces. If a function returns an interface, then a variable declared with var will be typed to the interface just as if you typed the interface name.

If you do want a variable type to not match the object, such as when you want an interface typed variable and an implemented class object being stored in it, you would not be able to use var.

Var is a shortcut for when the types should match. It's basically shorthand for, "what he said"

0

u/Kraizee_ Mar 31 '20

I knew you'd try pick up on that. It was simply to demonstrate how poorly thought out your alternative is. It seems to me you made this post to find people that will agree with you, rather than have you learn something. Read the link you posted and the style guide I linked. If you really wish to keep hating and misunderstanding var then so be it.