r/java • u/BitBird- • Jan 12 '26
Java's `var` keyword is actually really nice for cleaning up verbose declarations
I avoided var for years because I thought it made code less readable. Tried it last week and I'm a convert.
Instead of:
Map<String, List<CustomerRecord>> customersByRegion = new HashMap<>();
Just:
var customersByRegion = new HashMap<String, List<CustomerRecord>>();
The type is right there in the initialization. Your IDE still knows what it is. It's not like JavaScript where var means something totally different.
Really shines with streams and complex generics where you'd normally write the type twice for no reason. Also makes refactoring easier since you're not updating the type in two places.
Still feels weird after typing out full declarations for 10+ years but I get it now.
199
u/ablativeyoyo Jan 12 '26
Amen. Type inference is not dynamic typing.
65
u/manifoldjava Jan 12 '26
I use it only when it improves clarity. The case you mentioned is the primary one, when a new expression, esp. of a parameterized type, in on the RHS. Other cases include where the type is generated, long, or complicated - I find it best to use var and rely on the IDE for type discovery for these.
Otherwise, var hides information, which makes code harder to read.
22
u/TheTrailrider Jan 12 '26
It really shines when you're trying to iterate Map entries using for loop
7
u/Reasonable-Total-628 Jan 12 '26
i like this in this case, not so mich for method calls
11
u/AnonAreLegion Jan 12 '26
I don't think there are any meaningful differences in your two initialization examples. They are equally easy to understand.
I dislike var for this reason, it's either neutral or negative regarding code comprehension.
235
u/waywardcoder Jan 12 '26
be aware that the type of your variable changed from Map to HashMap. Sometimes that matters.
32
u/adwsingh Jan 12 '26
Java also provides a style guide that explains when type inference enhances readability and when it doesn’t.
https://openjdk.org/projects/amber/guides/lvti-style-guide
11
u/njitbew Jan 12 '26
> Tried it last week and I'm a convert.
The only things I dislike about var:
It's really useful for ad-hoc code though (e.g., jshell, sharing snippets).
23
u/mightygod444 Jan 12 '26
While I totally agree overall, your example is a strange one. Generic types verbosity was already addressed and reduced in Java 7 with the empty diamond operator syntax. Makes no sense IMO to go back to introducing this with the use of var.
Where var really shines is for those verbose Java style classes where the variable name is usually just the class name anyways, e.g.
BeanServiceCloneBridgeClientFactory beanServiceCloneBridgeClientFactory = new BeanServiceCloneBridgeClientFactory();
Becomes:
var beanServiceCloneBridgeClientFactory = new BeanServiceCloneBridgeClientFactory();
Much cleaner!
12
u/pellets Jan 12 '26
Know what would be even nicer? Type aliases. So you only have to declare some large generic thing once,
3
u/Little_Blackberry Jan 12 '26
I'm older I guess. I don't really like use it.
8
u/jvtsjsktpy Jan 12 '26
Agree. Wish we have
constorletas a shorthand forfinal varlocal variables to make the declaration even more concise.2
u/oss-dev Jan 12 '26
Type inference isn’t dynamic typing. It’s Java admitting the compiler is better at repetition than we are.
2
u/Daniel_Kummel Jan 12 '26
When I worked for a company that used C#, i was told to always use var. Doing Java projects with colleagues in uni, I was criticized for using it. Then, at my current work, when I work in Java projects, no one minds it, but I'm the only one writing it.
Is there a flaw to var specific to Java?
2
u/BenchEmbarrassed7316 Jan 12 '26
This works even better in languages where the type is written after the name:
IDE displays as
The IDE will add the type (in a different color) on its own. You can double-click on it to insert it into your code.
But you won't see the type in github for example. This is a drawback.
2
u/atehrani Jan 18 '26
For local scoped instantiations I agree. But I dislike for local vars such as
var date = getDate();
Now when I review a PR, I don't know what type it is. String? DateTime? Long?
6
u/MkMyBnkAcctGrtAgn Jan 12 '26
90% of the time I see it being used in the wild in ways it was not meant for. Saw one codebase in our org that basically just used var everywhere. It's easier to disallow it in a style guide nowadays than to debate a proper utilization.
2
u/Minecraftian14 Jan 12 '26
Okay... I have never had any complaints with var, i use it all the time, but I just noticed something from your examples!
It's better to hide the type in the latter (construction) part, rather than the first (datatype).
For example, imagine this:
ACustomDataClass<Customer> customersByRegion
= new (with some specific args, now much clear);
In original example, due to the excessive length of the class name and type args, the arguments are pushed off to the far right. Now this is purely cosmetic, i believe hiding the latter part and explicitly putting = new on new line is much more readable.
Both have their own disadvantages though.
Iirc, i think cpp has a similar instantiation syntax?
Probably one can also do something like.
MyClass instance = new MyClass
(The arguments here);
Now I'm thinking which one is better.
2
u/rlrutherford Jan 12 '26
Ha!
Was doing serious soap/xml, ~20 years ago, multiple classes, (dozen + ) with the same class name but different package due to XML.
The var keyword would have done wonders because same f-n class name, but different import packages.
That said, I've seen var abused in .net and generally prefer explicit class names.
1
u/Personal-Search-2314 Jan 12 '26
As a majority dart developer, when I hop on Java- the lack of type inference (it’s gotten better) and nullsafety makes me want to cry.
On a new Springboot project I would love to see how Kotlin feels.
1
u/Medical_Amount3007 Jan 12 '26
I really promote var in Java, auto in C++(newer) and I from time to time get into arguments. But it really is nice to read the code and write the code. So keep it up with var x = ”awesome”;
1
u/__konrad Jan 12 '26
Maybe unpopular opinion, but I think final class fields should also support
var1
u/audioen Jan 12 '26
It's not just that. It allows you to also reference anonymous classes, e.g. var foo = new Xyz() { ... }; which has no name as such. I appreciate what few conveniences Java can give me, and this is one of those.
1
u/freekayZekey Jan 12 '26
i hate using it for generics lol. pretty good with the method name makes sense tho or in situations where it’s simple object declarations like
var customer = new Customer(…)
1
u/wildjokers Jan 12 '26
What's the difference? You still have to type the types in the diamonds at least once, you just moved it to the right. Doesn't seem to offer any advantage to me. Also, now customersByRegion is a HashMap instead of a Map, which probably doesn't matter, but could.
1
u/aoeudhtns Jan 12 '26
Also look at /u/jodastephen's new Java best practices. Some really interesting stuff on how var works in destructuring pattern matching (among other things).
But yes, I've relaxed from "never" to finding it handy -- especially when the type information is redundant like
Foo foo = new Foo() / var foo = new Foo(). I also like using it when iterating so as to not repeat the inner type. I would also posit to skeptics that they're already likely "using" it in its implicit form with lambdas.1
u/RICHUNCLEPENNYBAGS Jan 12 '26
I set up a Checkstyle rule on my last team where we required var except in cases where a type was truly required (I forget what those are at the moment). I’m not trying to look at all that line noise
1
u/Joram2 Jan 12 '26
Yes. Welcome to 2018!
1
u/Ketroc21 Jan 13 '26
I typically care more about the information I get from the type, than the variable name itself.
..but I feel like var is becoming the new standard so I'm adapting to it. Side note, you can have intelliJ display the type for you next the vars (works for lambdas too which also hide the types)
1
u/plainnaan Jan 13 '26
I only use var for direct object instantiation using the new keyword and for explicit casts.
These are the only two cases where it is crystal clear which type the variable has from only looking at the statement without the help of an IDE, which is important for web based code reviews/diffing.
1
u/GiantsFan2645 Jan 14 '26
I’d still rather have verbose but clear declaration and initialization over this method. Code base I work on is quite large and knowing exactly what data types I’m working with at a glance is much more valuable to me. Usually on my team if you are using var, it needs to be abundantly clear what the structure is
1
u/bananadick100 Jan 14 '26
The use of var lies when you have multiple classes with the same name in different packages. For production code that's it for me. Var is awesome when prototyping or anytime you don't really care about the readability/maintainability of the code
1
u/BanaTibor Jan 20 '26
You have achieved nothing. Actually this is the situation where var is worse than the original. Use it in a loop to declare a looping variable, use it for some very limited scope temporary variable. For anything else it is a bad thing.
1
u/Pekyeet Apr 18 '26 edited Sep 21 '26
The original post content no longer exists here. The author used Redact to remove it, exercising their right to control their data & privacy.
Aspiring middle mitten imagine sand walnut ring
1
u/ducki666 Jan 12 '26
It took you 8 years to find out? 😃
1
u/[deleted] Jan 12 '26
I love verbose language! I hate abstraction.
1
u/Qinistral Jan 12 '26
This is one of those things that attracted me to Scala. So glad Java got it too.
0
u/klimaheizung Jan 12 '26
Wait until you try Scala. It had the same thing for over 15 years, but it's even better, you basically just need "val customersByRegion = HashMap(List())" and you are done. Neat, isn't it?
-2
u/chambolle Jan 12 '26
When var appeared, we were heavily criticized if we had the audacity to criticize this addition to the language and doubt its contribution. Years later, we realize that this keyword hasn't really changed much. It's a shame that those who downvoted any criticism don't come forward to admit their mistake.
0
u/[deleted] Jan 12 '26
[deleted] — view deleted comment
0
u/[deleted] Jan 12 '26
[deleted] — view deleted comment