https://kotlinlang.org logo
#reflect
Title
# reflect
j

jaqxues

10/15/2020, 8:09 PM
Hello, I need to store a type (either a KClass or a KType) and was wondering whether it even make sense to want to store a simple type as KClass, or does it not matter if I have everything as KType (regarding space efficiency). Intuitively, I would not use the java-reflect-Type since it seemed more complex than simply Class, but I was wondering if that actually holds up. So what takes less space, a KClass or a KType (String::class or typeOf<String>())
u

udalov

10/16/2020, 8:11 AM
KType takes more space because it consists of classifier (which is KClass for class types) + generic argument types + nullability + annotations
j

jaqxues

10/16/2020, 8:56 AM
Is there a way i can check if a reified type is generic? So i can simplify the api to always use a generic, and not let the user either use a KType or a KClass. From
fun <T: Any> withType(type: KClass<T>)
and
fun <T> withType(type: KType)
To
inline fun <reified T>()
Something like
if (isGeneric<T>) typeOf<T>() else T::class
Also when the type is nullable, use a KType ig. For that
null is T
would work though I think.
u

udalov

10/16/2020, 9:32 AM
I recommend to choose based on specific properties of KType, I think it’ll be a bit clearer:
Copy code
val type = typeOf<T>()
if (type.isMarkedNullable || type.arguments.isNotEmpty()) type else T::class
j

jaqxues

10/16/2020, 9:46 AM
That works ig, thanks!
2 Views