为什么我们不能将两个推断变量作为匿名 class 分配给彼此?

Why can't we assign two inferred variables as an anonymous class to each other?

Java 10 允许用 var 做一个 anonymous class 像:

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

但是这个赋值会抛出一个错误:

a1 = a2;

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

根据错误日志,为什么 Java10 不能将两个推断的 var 作为 anonymous class 分配给彼此,但它可以对其他类型执行相同的操作像 LongString 等?

每个 new Object(){} 创建一个新类型(匿名 class)。这些类型没有 subtype-supertype 关系,因此无法将 a1 分配给 a2,反之亦然。

但是当你有两个 long 变量时,它们实际上具有相同的类型 long,因此它们可以相互赋值。