Giorgio Spilorcio
09/30/2024, 10:50 AMreified type parameters in non-inlined functions by passing the Class<T> as an additional parameter at runtime? For example:
fun <reified T : A> doStuff(s: String): T {
Debug.log(T::class.java)
}
would compile in the JVM to:
public static final <T extends A> void doStuff(Class<T> reifiedType, String s) {
Debug.log(reifiedType);
}
Can this feature be added to Kotlin or would it require big changes?ephemient
09/30/2024, 11:21 AMreified T can do that Class<T> cannotchrisjenx
09/30/2024, 12:59 PMGiorgio Spilorcio
09/30/2024, 1:40 PMGiorgio Spilorcio
09/30/2024, 1:41 PMno, there are thingsCan you tell me an example please?can do thatreified TcannotClass<T>
ephemient
09/30/2024, 1:43 PMClass is a Java concept so
val a: Class<out Any> = List::class.java
val b: Class<out Any> = MutableList::class.java
a == bephemient
09/30/2024, 1:44 PMKClass has limitations, such as having generics erased, while reified T isn'tephemient
09/30/2024, 1:53 PM<T> can be nullable or non-nullable, and `Class`/`KClass` are always non-nullable, and if you define
inline fun <reified T> emptyArray(): Array<T> = Array(0) { TODO() }
then it's safe to call emptyArray<String>() and emptyArray<Int>(), but if you define
fun <T> emptyArray(clazz: Class<T>): Array<T> = java.lang.reflect.Array.newInstance(clazz, 0) as Array<T>
then while emptyArray(String::class.java) works, emptyArray(Int::class.java) will throw a ClassCastException because primitives in Java are deeply special