2

Java 10 allows to do an anonymous class with a var like:

var a1 = new Object(){};
var a2 = new Object(){};

But this assignment will throw an error:

a1 = a2;

jshell> a1 = a2; | Error: | incompatible types: $1 cannot be converted to $1 | a1 = a2; | ^^

Based on the error log, why can't Java 10 assign two inferred vars as an anonymous class to each other, but it can do the same for other types like Long, String, etc.?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hoan
  • 1,058
  • 8
  • 13
  • 11
    Because they are **not** the same! An anonymous class is exactly that, an anonymous `class` that inherits from `Object` - one is `Object$1` and the other is `Object$2`. It's like asking why you cannot assign an `ArrayList` to a `HashSet`. – Boris the Spider Mar 30 '18 at 19:40
  • 1
    @BoristheSpider are they both `$1`? from the error log: `$1 cannot be converted to $1` – hoan Mar 30 '18 at 19:43
  • It's more of a problem with the jshell error message it seems. `javac` uses ` cannot be converted to ` (not necessarily the _same_ `` though) – Jorn Vernee Mar 30 '18 at 19:45
  • 5
    `$1 cannot be converted to $1` looks like bug. When we remove `a1 = a2;` assignment and compile such code we will get (as expected) two anonymous classes with `$1` and `$2` suffixes. So expected error message should look more like `$2 cannot be converted to $1`. – Pshemo Mar 30 '18 at 19:56
  • 3
    Because they are not the same type. They are two different anonymous subtypes of `Object`, and neither is a subtype of the other. – Brian Goetz Mar 30 '18 at 21:36

1 Answers1

10

Each new Object(){} creates a new type (an anonymous class). These types have no subtype-supertype relation, so it is not possible to assign a1 to a2 and vice versa.

But when you have two long variables, both actually have the same type long, so they are mutually assignable.

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72