In java, why not expand the window?

In java we can embed and then expand. Why can't we expand and close the box? For example:

class WidenAndBox{ static void go(Long x) { } public static void main(String [] args) { byte b=5; go(b); } } 

Compiler error

+4
source share
5 answers

I'm not used to how the specification was written, but overall you do not automatically switch between incompatible classes. Extending primitives is a separate issue, and Java extension rules were laid down long before autoblock was added to the language. This is a trade-off between letting the compiler catch your mistakes and not annoy you with small details.

In the case of your example, if you have an autoboxed long, you will be fine or if you made a function that took Number as a parameter, you would be fine too. You might think that the compiler should help you, realizing that the byte can be easily unpacked and reinstalled as long, but the people who make the compiler disagree, and I don’t do that either.

+6
source

It is possible for the compiler to perform a boxing operation followed by an extension operation to match the method call. Take an example

  class BoxAndWiden { static void go(Object o) { Byte b2 = (Byte) o; // ok - it 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 ? } } 

Compiles (!) And produces the result: 5 Let me show you how this works behind the scenes. When the JVM hits the line that calls the go () method:

  • Byte b is placed in byte.
  • The byte reference has been expanded to an object (since Byte extends Object).
  • The go () method received an Object reference, which actually refers to the byte object.
  • The go () method returns the Object link back to the Byte link (re member, in this script there has never been an object of type Object, only an object of type Byte!).
  • The go () method printed the byte value.

But in your case. Why didn't the compiler try to use the box-then-expand logic when it tried to cope with the WidenAndBox class?

if he first tried to check the box, the byte would be converted to byte. Now we are again trying to expand the byte to a long one, and, of course, the IS-A test fails.

+3
source

Set it to long.

+1
source

Just add it to the long type

  go( (long) b); 
+1
source

I believe that the main reason is performance. If you allow an arbitrary combination of extension and (un) box, you will need to check for more suitable methods. Especially in the context with functions, it takes several primitive parameters of a small range, the number of possible combinations can become quite large.

+1
source

All Articles