Auto-(un)boxing fail for compound assignment

让人想犯罪 __ 提交于 2019-12-08 16:37:19

问题


Thanks to the implicit casting in compound assignments and increment/decrement operators, the following compiles:

byte b = 0;
++b; b++; --b; b--;
b += b -= b *= b /= b %= b;
b <<= b >>= b >>>= b;
b |= b &= b ^= b;

And thanks to auto-boxing and auto-unboxing, the following also compiles:

Integer ii = 0;
++ii; ii++; --ii; ii--;
ii += ii -= ii *= ii /= ii %= ii;
ii <<= ii >>= ii >>>= ii;
ii |= ii &= ii ^= ii;

And yet, the last line in the following snippet gives compile-time error:

Byte bb = 0;
++bb; bb++; --bb; bb--; // ... okay so far!
bb += bb; // DOESN'T COMPILE!!!
// "The operator += is undefined for the argument type(s) Byte, byte"

Can anyone help me figure out what's going on here? The byte b version compiles just fine, so shouldn't Byte bb just follow suit and do the appropriate boxing and unboxing as necessary to accommodate?


Extra question

So is there a way to make compound assignment operators work with Byte, Character, and Short on the left hand side, or are they simply illegal(!!!) for these types?


回答1:


Section § 5.1.7 (Boxing) of the standard says:

From type boolean to type Boolean
From type byte to type Byte
From type char to type Character
From type short to type Short
From type int to type Integer
From type long to type Long
From type float to type Float
From type double to type Double

Note there is no int to Byte. When you do bb + bb it's converted to int + int, which isn't boxed back to Byte. For the byte version, int + int is cast back to byte directly (narrowing primitive conversions, § 5.1.3) so it's allowed.



来源:https://stackoverflow.com/questions/2704540/auto-unboxing-fail-for-compound-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!