AFAIK, var
is not keyword in Java. It is reserved type name. I wonder that in what circumstances we should use/avoid it. Are there principles about its usage?
import java.util.HashMap;
public class Test {
public static void main(String[] args) {
var x = new HashMap<> (); // legal
var y = new HashMap<String, Integer>(); // legal
var z = "soner"; // legal
System.out.println(z);
var umm = null; // xx wrong xx //
var foo; // xx wrong usage without initializer xx //
var var = 5; // legal
}
}
I know one reason, that we actually use in our project. Whenever there is a variable that is "big" we replace it with var. For example:
I find the second example a lot more readable, and this is how we mainly use it.
There is another example where this could be used (but I am not using it so far). Previously this was possible via chaining only for lambda expressions for example, as this would be a type known by the compiler only - they could not be declared.
You could use it for anonymous classes too, i.e. there is just no type to declare. E.g.
I can see one drawback to use
var
aka "Local type-inference":In that context, you need to check the signature of
getInstance(String)
method to know what will bey
type.EDIT:
Since there is a discussion about the name of my variables not being really correct, let's use some real example then.
What type is
date
?I could call
I don't believe the solution would be to use a full name either.
So instead, in that case I would not use type inference
Note: Can someone tell me if this require the import of
LocalDate
if I usevar
(note that I use a method in a different class, so I never had to declareLocalDate
in this class).I will answer myself if I find the time to install a JDK10.