Local type inference in Java
A quick look
I like playing with different programming languages and comparing their features. Java 10 gained local type inference through var. So, let’s take a look how this works. First, you may be asking yourself Why isn’t he writing keyword?. That is, because var is not a keyword but a reserved type name. This means that if you have been using var as a variable name your code won’t break.
var var = 42;
What does not work, though, is
var a;
Here the initializer is missing, thus the expression makes no sense. The following does not work, either:
public static var a = “Hallo”;
public var a = “Hallo”;
Local type inference means that you can use var in methods and blocks, but not for static or instance variables. So, this one works:
public static void main(String [] args) {
var var = 42;
for (var i = 1; i <= var; i++) {
var pow2 = i*i;
System.out.println(pow2);
}
}
I like this new feature quite a bit. Not primarily because we can spare a few characters but because we do not have to repeat ourselves:
List<String> l1 = new ArrayList<>();
var l2 = new ArrayList<String>();
It is, however, worth mentioning that in other languages there are debates on when to use var and when to be more specific. If you have something like
var result = aMethod();
it is not immediately clear which type result has. But this matters in other programming languages, too. So, what do you think about var in Java?
A previous version of this article was published 2018/04/02 on my Blogger.com blog Tommis Blog. I deleted the weblog in the wake of the GDPR (General Data Protection Regulation), so the original post is no longer available (or only through the Wayback machine of the Internet Archive).
If not stated otherwise images are © Thomas Künneth