I don't get why java doesn't do the widening and then autoboxing.
Integer i = (short) 10;
I would think the following would take place:
10 to short.short would then widen to int.int would then autobox to Integer.Instead it's a compilation error.
Example 2:
Short x = 10;
Integer y = x;
This fail too.
According to the JLS, Section 5.2, which deals with assignment conversion:
Assignment contexts allow the use of one of the following:
an identity conversion (§5.1.1)
a widening primitive conversion (§5.1.2)
a widening reference conversion (§5.1.5)
a boxing conversion (§5.1.7) optionally followed by a widening reference conversion
an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
It is unable to apply two conversions at once (widening primitive conversion and boxing conversion); only one conversion can apply here, so it has to result in an error.
The solution would be to cast the short back to an int (a casting conversion), which would allow the assignment conversion to be a boxing conversion:
Integer i = (int) (short) 10;
(Or here, don't cast it to short in the first place.)
Integer i = 10;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With