3 ms·
Why would you write code without an IDE? And using var doesn't suddenly make things happen randomly, everything is still perfectly well defined, just less verb
by danbruc 11y ago
Why would you write code without an IDE?
And using var doesn't suddenly make things happen randomly, everything is still perfectly well defined, just less verbose. And it is a feature that 99.9 % of the time does what you want, situations in which you want a different type than the inferred one are rare in practice. Actually the only one that I can remember is initializing a variable with some concrete implementation of an interface and desiring the interface type instead of the concrete type. And this one occurs pretty rarely because I think aiming for single assignment is a good thing.
- gravypod 11y ago>And it is a feature that 99.9 % of the time does what you want While typing a variable name explicitly is a feature that 100% of the time does what you want.
- danbruc 11y agoThat is why you have the choice to be explicit. You choose between shorter and less redundant code and full control over the type of the variable. What is the point of typing out the same type in a single line twice? HashMap<String, AtomicReference<Foo>> fooMap = new HashMap<String, AtomicReference<Foo>>(); What is the disadvantage of using var? var fooMap = new HashMap<String, AtomicReference<Foo>>(); It's less redundant, easier to read, does not clutter the code and has exactly the same information content. And if you really want the variable to be of type Map<,> nobody stops you.
- whitenoice 11y agoI don't think you have to type it twice even now, if you specify the type on the left, you can just specify <> on the right. So you can write something like - Map<String, List<Xyz>> foo = new TreeMap<>(); This has been present from Java 7. The reason I like this is that when you are parsing through some library code you can just look at the variable declaration and ignore its initialization to figure out what type it is.