https://kotlinlang.org logo
Title
m

mbonnin

01/08/2019, 2:29 PM
This decompiles as
List listOfDouble = CollectionsKt.listOf(1.0D);
      if (listOfDouble == null) {
         throw new TypeCastException("null cannot be cast to non-null type kotlin.collections.List<kotlin.Int>");
      } else {
         int first = ((Number)listOfDouble.get(0)).intValue();
         System.out.println("first=" + first + " (" + Integer.TYPE.getName() + ')');
      }
p

phldavies

01/08/2019, 2:31 PM
So the reason the cast is not failing is due to the unboxing?
m

mbonnin

01/08/2019, 2:31 PM
No idea. From my understanding, a conversion from Double to Int is made which is different from a cast
A cast would have most likely failed
But really not sure what's happening
p

phldavies

01/08/2019, 2:33 PM
I think it's attempting to do a conversion from
Integer
to
int
but through a cast to the
Number
superclass to invoke the
intValue()
method. Because of this it's actually casting the boxed
Double
value to
Number
(which succeeds) instead of the expected cast of the
Double
to
Integer
which would fail
d

Dico

01/08/2019, 11:24 PM
The conversion from boxed Int to Int is identical to the conversion from boxed Double to Int because it uses Number superclass.
Ok what Phil said
m

mbonnin

01/09/2019, 8:36 AM
I see. That feels weird though
d

Dico

01/09/2019, 8:38 AM
Weird things can happen when you cast generic type parameters. It's not advisable.