Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java why not widen then box?

Tags:

java

core

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

like image 416
giri Avatar asked Jan 12 '10 18:01

giri


1 Answers

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.

like image 195
Greg Charles Avatar answered Oct 27 '22 07:10

Greg Charles