scala/bug

Unnecessary boxing of AnyVal values when invoking getClass

carymrobbins opened this issue · 1 comments

Maybe I'm missing something, but it seems invoking getClass does unnecessary boxing when applied to AnyVal values.

https://gist.github.com/carymrobbins/ec94e043e1fb1ce20501f1808672b9f9

To summarize -

1.getClass returns the int primitive class, but actually does some boxing when looking at the bytecode. I'm not sure why this would be necessary.

1.asInstanceOf[Int with Tag].getClass returns the boxed java.lang.Integer class, even though removing the .getClass returns a primitive int value.

Because of this magic boxing performed in the bytecode, it makes it hard to inspect things at runtime to figure out if we're really dealing with a primitive or boxed value (particularly needed in test suites). Maybe there's a better way to get around that (welcoming suggestions), however, the superfluous boxing seems like something that should be removed.

But it seems like even 1.asInstanceOf[Int with Tag] is boxing and then immediately unboxing (making trait Tag extends Any doesn't change that):

0: iconst_1
1: invokestatic  #30                 // Method scala/runtime/BoxesRunTime.boxToInteger:(I)Ljava/lang/Integer;
4: invokestatic  #51                 // Method scala/runtime/BoxesRunTime.unboxToInt:(Ljava/lang/Object;)I
7: ireturn