Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does var<T> do in Java?

A friend of mine noticed that

var<Integer> list = new ArrayList<Double>();

was valid in Java. It turns out that the type of list is evaluated to ArrayList<Double>.

When using var<Integer> list = new ArrayList<>();, list is just ArrayList<Object>.

Both of us were not able to figure out, what the generic type of var does, as it seems to be ignored. But if so, why is this even syntactically correct in the first place?

like image 432
Joja Avatar asked Feb 21 '20 00:02

Joja


People also ask

What is var used for in Java?

var can be used in a local variable declaration instead of the variable's type. With var , the Java compiler infers the type of the variable at compile time, using type information obtained from the variable's initializer. The inferred type is then used as the static type of the variable.

Is it good to use var keyword in Java?

Motivation for var keyword: Remember, that the only purpose of using var , according to the design of the language (since JDK 10+) is to beautify the code and make it more readable. var only serves the cleaner/better readability purpose and it does NOT amend the type system of the Java language.

Why VAR is not working in Java?

The reason may be you are using an older version of java. In Java 10, the var keyword has been introduced. e.g. instead of doing String str = "Java" , you can now just say var str = "Java" .


2 Answers

This is indeed a bug, but the proof lies in the Java Language Specification § 14.4 Local Variable Declaration Statements:

LocalVariableType:
    UnannType
    var

Ad you can see, the restricted identifier var is listed without any other token. Also, UnannType eventually resolves to the token TypeIdentifier which explicitly forbids var.

So no, var<Integer> is not valid.

like image 166
MC Emperor Avatar answered Oct 17 '22 18:10

MC Emperor


As it turns out, the usage of var<T> is only allowed in Eclipse with JDT core, javac does not accept this. Therefore, I assume this is a bug in Eclipse.

EDIT: As @MC Emperor showed, this is definitely a bug. I have added this bug to the Eclipse Bugzilla.

like image 25
Joja Avatar answered Oct 17 '22 17:10

Joja