Search code examples
kotlincasting

Why can't I cast an Integer to a Long in Kotlin?


It seems this should be safe to do?

@Test
fun testCast() {
    val storeId : Any = Int.MAX_VALUE
    val numericStoreId = if(storeId is String) storeId.toLong() else storeId as Long
}

This yields:

java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.Long

Why is Kotlin not allowing this? Our Kotlin version is 1.6.

The fix is writing val numericStoreId = if(storeId is String) storeId.toLong() else (storeId as Number).toLong() instead, but I don't get why it is required.


Solution

  • You can't do it in Java either. They simply aren't the same types.

    What you're trying to do is equivalent to this:

    Integer i = 0;
    Long l = (Long) i;