var infers a local variable's type from its initialiser. The type is still static and fixed at compile time.
The problem it solved
Declarations repeated long generic types on both sides of the assignment, adding length without adding information.
How you did it before
Writing the full type twice, as in Map<String, List<Order>> m = new HashMap<>(), with the diamond operator as the only relief.
var list = new ArrayList<String>();
list.add("still statically typed");
System.out.println(list.get(0));
var map = new HashMap<String, List<Integer>>();
map.put("k", List.of(1, 2));
for (var e : map.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
still statically typed
k -> [1, 2]Asked as
- Where can you use var, and where can you not?
- Does var make Java dynamically typed?
- When does var hurt readability?
Scenario question
A reviewer objects to var in a pull request, saying it makes the code harder to read. The line is var result = service.process(input).
Do they have a point?
What a good answer weighs
Yes, in this instance. var works well when the initialiser names the type — var list = new ArrayList<String>() — and badly when the type comes from a method whose name does not reveal it. The principle is whether a reader can tell the type from the line alone, which is a judgement about readability rather than a rule about the keyword.