Reputation: 87
When I run the following on the Scala 2.10 REPL:
classOf[Int].cast(1)
I get the following error:
java.lang.ClassCastException: Cannot cast java.lang.Integer to int
at java.lang.Class.cast(Class.java:3176)
at .<init>(<console>:18)
...
Why is this happening?
Upvotes: 0
Views: 299
Reputation: 5919
This is because of autoboxing. It is a common feature, not only found in Scala, but also in Java.
The int
value needs to be passed to the cast
method as an object. But an int
is not an object, so the compiler introduces a conversion to an instance of java.lang.Integer
. And that's a different type than int
, it's as simple as that.
This one should work:
classOf[java.lang.Integer].cast(1)
Upvotes: 2