What does var<T> do in Java?
Asked Answered
A

2

9

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?

Amylase answered 21/2, 2020 at 0:51 Comment(6)
Java 10 says Main.java:5: error: illegal reference to restricted type 'var' var<Integer> list = new java.util.ArrayList<Double>();.Zohara
@Zohara We originally tried this on Eclipse where this was indeed a perfectly valid program. In response to your comment, I've just tried it with javac and there, this is indeed incorrect.Amylase
@Zohara AFAIK, it does not, as it uses a custom compiler. Well, at least this works in Eclipse, you may try this yourself if you want. :-)Amylase
@ggorlen: https://mcmap.net/q/1314488/-which-java-compiler-is-used-by-eclipseJequirity
Java 11(?) introduced the concept that you don't need to declare a variable if it's initialised in the same line, ie List<Integer> list = new ArrayList<Double>(); can now be var<Integer> list = new ArrayList<Double>(); ... because typing is hard for some people 🙄. This is only available, AFAIK to local variables (ie within a closed context)Huang
Ah, I see you're right. I don't use Eclipse so I learned something new. I guess I'd edit the post then to mention this is specific to ECJ.Zohara
D
5

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.

Disseminate answered 6/5, 2020 at 15:43 Comment(0)
A
8

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.

Amylase answered 21/2, 2020 at 1:15 Comment(1)
Bugzilla entry: bugs.eclipse.org/bugs/show_bug.cgi?id=560999Pharmacist
D
5

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.

Disseminate answered 6/5, 2020 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.