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?

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
Joja
  • 370
  • 2
  • 11
  • 3
    Java 10 says `Main.java:5: error: illegal reference to restricted type 'var' var list = new java.util.ArrayList();`. – ggorlen Feb 21 '20 at 00:55
  • 1
    @ggorlen 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. – Joja Feb 21 '20 at 01:00
  • 2
    @ggorlen 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. :-) – Joja Feb 21 '20 at 01:02
  • 1
    @ggorlen: https://stackoverflow.com/a/47623570/869736 – Louis Wasserman Feb 21 '20 at 01:04
  • Java 11(?) introduced the concept that you don't need to declare a variable if it's initialised in the same line, ie `List list = new ArrayList();` can now be `var list = new ArrayList();` ... because typing is hard for some people . This is only available, AFAIK to local variables (ie within a closed context) – MadProgrammer Feb 21 '20 at 01:04
  • 1
    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. – ggorlen Feb 21 '20 at 01:04

2 Answers2

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.

Joja
  • 370
  • 2
  • 11
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.

MC Emperor
  • 22,334
  • 15
  • 80
  • 130