Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 924
polygenelubricants Avatar asked Apr 24 '10 13:04

polygenelubricants


1 Answers

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.

like image 159
JRL Avatar answered Oct 16 '22 07:10

JRL