Java += 运算符
Java += operator
据我了解 x+=1 与 x=x+1 一样工作,但为什么它在 String 中不起作用?
String str = "";
str = str + null + true; // fine
str += null + true; // Error message: The operator + is undefined for the argument type(s) null, boolean
在Java、expression are evaluated from left to right。于是
str = str + null + true;
与
相同
str = (str + null) + true;
和 null
和 true
隐式转换为 String
。这是有效的,因为在 str + null
中,编译器知道 str
是一个 String
并将 null
转换为 String
。这是可能的,因为每个值都可以转换为 Java 中的 String
。通过相同的论证,编译器知道 (str + null)
是 String
,因此将 true
转换为 String
.
另一方面,
str += null + boolean;
等同于
str = str + (null + boolean);
因此,首先评估 null + boolean
。由于未为类型 null, boolean
定义运算符 +
,因此生成 compiler-error。
据我了解 x+=1 与 x=x+1 一样工作,但为什么它在 String 中不起作用?
String str = "";
str = str + null + true; // fine
str += null + true; // Error message: The operator + is undefined for the argument type(s) null, boolean
在Java、expression are evaluated from left to right。于是
str = str + null + true;
与
相同str = (str + null) + true;
和 null
和 true
隐式转换为 String
。这是有效的,因为在 str + null
中,编译器知道 str
是一个 String
并将 null
转换为 String
。这是可能的,因为每个值都可以转换为 Java 中的 String
。通过相同的论证,编译器知道 (str + null)
是 String
,因此将 true
转换为 String
.
另一方面,
str += null + boolean;
等同于
str = str + (null + boolean);
因此,首先评估 null + boolean
。由于未为类型 null, boolean
定义运算符 +
,因此生成 compiler-error。