开发者

Auto-(un)boxing fail for compound assignment

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 compi开发者_运维百科le-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?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜