Arguments in favor of var
:
var
requires less typing. It's shorter and sometimes easier to read than let's say Map<Integer, ArrayList<String>>
.
var
requires less code changes if a return-type of a method call changes. You only have to change the method call, but not every place it's used.
var
encourages a more descriptive name for variables. I.e. var customer = new Customer();
rather than var c = new Customer();
.
- When you have multiple variable under one another of different types, the names all line up if they're all
var
, which wouldn't be the case with the types itself (unless the types coincidentally all have the same length).
Arguments against var
:
var
obscures the actual variable type. If the initializer doesn't return a clearly defined type, you may not be able to tell a variable's type.
- Using
var
is lazy. Although var
is certainly easier to type than Map<Integer, ArrayList<String>>
, if the variable name isn't named well, you'd have to search a lot deeper in order to know what it refers to.
var
makes it harder to know what the type of the underlying variable actually is.
- You can't use
var
in all cases. Like:
var i = 1, j = 2;
- Only one variable is accepted for var
at a time.
var arr = {1, 2, 3};
- Arrays must be explicitly declared.
var f = a -> a + " ";
- It cannot determine what type this lambda function is.
var f = String::replace;
- Method references cannot be used, because they don't have a type of itself. More info here.
Most of these are taken from this post for when to use var
in .NET C#, where the var
keyword has been present since the beginning, whereas with Java it's only available since version 10.
Oh, and another big advantage of var
: it's shorter for code-golfing (creating a program/function which does a certain task/challenge with as few bytes as possible). :) Probably the main reason why I don't mind that it was added, since I codegolf in Java (as well as .NET C#, 05AB1E, and Whitespace) pretty often.
Related: Java 7's diamond operator. List<String> names = new ArrayList<>();
vs List<String> names = new ArrayList<String>();
.
Personally I still use written out types instead of var
, except for code-golfing. But maybe I just need to get used to it a bit more before using it more often. For readability, and making it clearer and easier to see the type without having to dig, I don't use var
at all. As for Java 7's diamond operator, I only use it when I instantiate it directly after the field, but would not when I instantiate it elsewhere (i.e. I would use List<String> names = new ArrayList<>();
, but not List<String> names; /* ... some code here ...*/ names = new ArrayList<>();
).
In general it all comes down to preference, though.