Most of the days I have my life split between Java and C#. Work on one during the day, enjoy the other during the night. Some things I like in one language, some I prefer in other; it all depends on situation. But there is one feature I miss daily in Java. It is the var
keyword.
Simplest scenario would be:
var x = new Something();
In this case var
does not signify some new data type but it simply says to compiler to infer most appropriate type on its own. It is not variant data type by any stretch of imagination (check dynamic
for that) because var
still statically assigns a type. Finally compiled code is actually equivalent to:
Something x = new Something();
In this, most basic scenario, it is already quite helpful in avoiding repetition. But it gets better. If you are dealing with loop, you don't need to remember which kind of collection you are going in:
foreach (var item in foo.getItems()) {
item.doSomething();
}
Assuming getItems()
returns IList<MyItem>
, this code might get compiled as:
foreach (MyItem item in foo.getItems()) {
item.doSomething();
}
As long as MyItem
type contains doSomething()
, everything just works. If getItems()
returns list of String
, compile will fail (doSomething()
is not a method of a String, at least not in current Java/C# version). If you ever refactor your code to use some other class, compile will still work as long as it contains same methods used elsewhere in code.
And that is the case where I miss it in Java the most. If I work with someone else's classes and it is obvious that some sort of collection is returned, why cannot language figure out this for me? Why do I need to tell it, for even most basic cases, what exactly I need? Just so it can triumphantly say that my type doesn't match what it expects? If compiler is smart enough to tell me my return type sucks, it should be smart enough to fill the data type itself.
While this var
keyword does save me some typing its primary benefit comes from a more relaxed workflow. It helps me get over gritty, boring, ultimately unimportant, details into the code that actually matters. It preserves my flow of thoughts and it does make me more productive.
I see this feature as a major reason why I find C# more comfortable language than Java. It is not (just) about this particular syntactic sugar. It is about a philosophy. While Java prefers cleanliness of language, C# makes work easy.
PS: And don't let me get started about how var
is used with anonymous types, a distant dream in Java.
Try Scala. It has syntax almost same as Java, it contains enough syntactic sugar to lose your teeth, and if you use it in functional way, it may even rewire your brain.