Is it possible to modify the Kotlin compiler to su...
# multiplatform
g
Is it possible to modify the Kotlin compiler to support
reified
type parameters in non-inlined functions by passing the
Class<T>
as an additional parameter at runtime? For example:
Copy code
fun <reified T : A> doStuff(s: String): T {
    Debug.log(T::class.java)
}
would compile in the JVM to:
Copy code
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?
e
no, there are things
reified T
can do that
Class<T>
cannot
c
Also Class is a java construct. So that wouldn't work on multiplatform anyway. It's best to use KType. Generally if you need more information at runtime but don't want to manually pass it through, that's where compiler plugins will generate extra code. Think descriptors for kotlinx serialization
g
I tought it was possible since extension functions did something similar
no, there are things
reified T
can do that
Class<T>
cannot
Can you tell me an example please?
e
well one is that
Class
is a Java concept so
Copy code
val a: Class<out Any> = List::class.java
val b: Class<out Any> = MutableList::class.java
a == b
but also even
KClass
has limitations, such as having generics erased, while
reified T
isn't
also
<T>
can be nullable or non-nullable, and `Class`/`KClass` are always non-nullable, and if you define
Copy code
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
Copy code
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