Skip to content

Latest commit

 

History

History
30 lines (25 loc) · 674 Bytes

File metadata and controls

30 lines (25 loc) · 674 Bytes

为什么+=这样的运算可以直接作用于不同的类型?

8710619

int a = 1;
long b = 2;
a = a + b // not allow
a += b  // allow

为什么前者不被允许而后者可以?

Answer

这是Java语言规范规定的

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

a += b

等价于

a = (int)(a + b);

笔者注

其实我觉得一些语法特性之类的没什么好说,全凭 语言设计者的一张嘴。没必要在这方面纠结。但是这是 这个问题赞数挺高的,所以收录了。