https://kotlinlang.org logo
Title
l

Landry Norris

07/12/2022, 7:30 PM
Is there a reliable way to determine the class of a reified generic, including typedefs? I tried a when(T::class), but I can’t use X::class when X is a typedef. I would like to distinguish X and Y, where X and Y are both typedefs for class Z.
The reason is that I’m writing a helper method for JNI methods. I need the signature of a method, so I am using reified generics in an inline method for this. I can check T::class against Int::class, Double::class, etc to get the proper signature. I can’t check against jstring/jobject, however, since both are typedefs for CPointers.
e

ephemient

07/12/2022, 7:39 PM
the problem with
KClass
is generic erasure, not typedef. try
KType
,
typeOf<X>()
l

Landry Norris

07/12/2022, 7:41 PM
I’ll take a look at that.
Is there a performance hit due to reflection? I should mention this is K/N, so I don’t know as much about reflection on K/N.
e

ephemient

07/12/2022, 7:47 PM
on JVM it does result in some kotlin-reflect machinery being loaded, but I don't know about K/N
l

Landry Norris

07/12/2022, 7:50 PM
I’ll have to try this out tonight and see if it helps.
I tried using a when with typeOf, but when I pass in a typeOf a typedef, it always triggers the when branch with the first type that has the same underlying class. If I have
when(type) {
    typeOf<jstring> -> "String"
    typeOf<jobject> -> "Object"
}
and pass in typeOf<jobject>, it returns “String”
where jstring and jobject are both typedefs for CPointer
e

ephemient

07/14/2022, 9:54 PM
oh, I see. there is
typedef jobject jstring
in
jni.h
. so they are 100% indistinguishable in C and in Kotlin.
l

Landry Norris

07/14/2022, 10:00 PM
Yeah. I'm trying to write a method that uses reified generics to automatically get the signature of a method. I have it working for everything except typedefs. The Kotlin signature is known at compile time, I just want to create a string using it.
e

ephemient

07/14/2022, 10:03 PM
typedef
doesn't really exist, you can think of every usage as being immediately substituted before compilation
l

Landry Norris

07/14/2022, 10:18 PM
Yeah. I may need to make some sort of compiler plugin