More efficient reified type check

Hi, I think that there should be way for efficient type check in reified functions

Lets check this artificial example

inline fun <reified T> storageEfficientList(vararg items: T): List<T> {
    return when (T::class) {
        Int::class -> (items as Array<out Int>).toIntArray().asList()
        Byte::class -> (items as Array<out Byte>).toByteArray().asList()
        else -> items.toList()
    } as List<T>
}

When used, it is converted to something like that:

...
if (Intrinsics.areEqual(
            var4,
            Reflection.getOrCreateKotlinClass(Integer.TYPE)
        )
    ) ArraysKt.asList(ArraysKt.toIntArray(`items$iv`)) else (if (Intrinsics.areEqual(
            var4,
            Reflection.getOrCreateKotlinClass(java.lang.Byte.TYPE)
        )
    ) ArraysKt.asList(ArraysKt.toByteArray(`items$iv` as Array<Byte?>?)) else ArraysKt.toList(`items$iv`))
...

I think that there should be efficient way to check the type, at least without reflection, in ideal way - filter out code dead code.

This would allow to create efficient alternatives for overloading with multiple type arguments - one method from user perspective, but multiple specialized implementation inside of method.

2 Likes