tags:

views:

200

answers:

4

Hi 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

+1  A: 

Cast it to a long.

Thorbjørn Ravn Andersen
A: 

Just cast it to a long type

 go( (long) b);
Anders Rasmussen
+6  A: 

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.

Greg Charles
A: 

I believe the main reason is performance. If you would allow an arbitrary combination of widening and (un)boxing, you would need to check for the existence of more possibly matching methods. Especially in a context with functions takes multiple small range primitive parameters, the amount of possible combinations could become quite large.

Confusion