Reputation: 27199
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
Upvotes: 5
Views: 767
Reputation: 2989
It IS possible for the compiler to perform a boxing operation followed by a widening operation in order to match an invocation to a method. Lets take an example
class BoxAndWiden {
static void go(Object o) {
Byte b2 = (Byte) o; // ok - it's a Byte object
System.out.println(b2);
}
public static void main(String [] args) {
byte b = 5;
go(b); // can this byte turn into an Object ?
}
}
This compiles (!), and produces the output:5 Let me show how it works behind the scene.when the JVM, got to the line that invokes the go() method:
But in your case.Why didn't the compiler try to use the box-then-widen logic when it tried to dealwith the WidenAndBox class?
if it tried to box first, the byte would have been converted to a Byte. Now we're back to trying to widen a Byte to a Long,and of course, the IS-A test fails.
Upvotes: 3
Reputation: 16841
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.
Upvotes: 2
Reputation: 2000
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.
Upvotes: 6