In java we can box and then widen. Why cant we widen and box? For ex:
class WidenAndBox{
static void go(Long x) { }
public static void main(String [] args)
{
byte b=5;
go(b);
}
}
Compiler error
I'm not privy to the how the spec was written, but in general, you don't automatically cast between incompatible classes. Widening of primitives is a separate issue, and the Java widening rules were laid out long before autoboxing was added to the language. It's a tradeoff between the letting the compiler catch your mistakes and not irritating you with small details.
In the case of your example, if you had autoboxed a long you would be OK, or if you had made a function that took Number as a parameter, you would be OK too. You may think the compiler should help you along by realizing that a Byte could be easily unboxed and reboxed as a Long, but the folks that make the compiler don't agree, and I don't really either.
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