Auto-(un)boxing fail for compound assignment
Asked Answered
F

1

8

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?

Filiation answered 24/4, 2010 at 13:5 Comment(0)
B
6

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.

Bigford answered 24/4, 2010 at 13:31 Comment(2)
I'd think that since there's int to byte, and there's byte to Byte, the compiler would figure out that there's a valid path from int to Byte after all! Apparently this is not the case? Is there a way to make the compound assignment work with an explicit cast perhaps?Filiation
Well obviously this would work bb = Byte.valueOf((byte)(bb + bb)), but aside from that I don't know.Bigford

© 2022 - 2024 — McMap. All rights reserved.