Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Any competent Java IDE automatically generates you a variable declaration from the expression you want to assign to it. It’s actually less keystrokes than having to type “var”. Unless you only use a simple editor that doesn’t perform static analysis, less typing is not a good excuse for using “var”.

Conversely, in Java you often use the diamond operator like in:

    List<String> items = new ArrayList<>();
(Half of which, again, is code completion in your IDE.)

That doesn’t work with “var”. You’d have to write:

    var items = new ArrayList<String>();
while losing the ability to constrain your variable to a narrower type.

The loss of directly seeing the type information in statements of the form

    var foo = bar(x, y);
should meet a very high bar, IMO.


I've found var preferable when reading code.

I've wrought my hands over this and eventually came to the conclusion that developers in every language that started with local type inference have embraced it. So I've mostly ignored my concerns and gone with "var for everything".

If you have trouble with a type then rename the function or variable (AKA your "foo" and "bar" example. The names are bad, fix them. Context matters, we have none here. No one has an editor that displays a single line of code at a time.). But in general we haven't had issues on our projects.

Beyond that, my IDE (Intellij) makes it easy to uncover the inferred type if I really need to be 100.00% sure what it is. In general I don't, because in general I don't care, and even before 'var' I was generally ignoring the type anyways.


I think there is a tasteful way to selectively use var where it makes sense.

Even in your example, narrowing the variable doesn't make much sense - you are in a local scope, you control everything. Narrowing is more meaningful in fields, where var won't work by design.

Locally a well-named variable is often significantly more important than some long, somewhat useless type signature, especially when the right hand side makes it clear.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: