Is the only way to get the KClass of a List type (...
# getting-started
b
Is the only way to get the KClass of a List type (say,
List<Int>
) to do
listOf<Int>().javaClass.kotlin
? I get complaints trying to do
List<Int>::class
m
these two give the same result
Copy code
println(listOf<Int>().javaClass.kotlin)
println(listOf<Int>()::class)
b
Ah, good catch, that's a bit better. I was hoping there was a way to avoid creating an instance though
m
the generic type gets erased anyway right? Maybe you are just looking for
List::class
?
b
That's actually what I'm playing with. In the KClass it's preserved
for example:
Copy code
val INT_LIST_TYPE = listOf<Int>()::class
fun <T : Any> getterFor(valueType: KClass<T>) {
    // println(valueType.isSubclassOf(List::class))
    when (valueType) {
        Boolean::class -> println("boolean")
        INT_LIST_TYPE -> println("int list")
        else -> println("other")
    }
}
Hmmm, also problematic is that
listOf<Int>()::class
does not much
KClass<List<Int>>
.
listOf
gives
KClass<out List<Int>>
and List<Int> is expected to be just
KClass<List<Int>>
.
Another thing I came up with: `
Copy code
inline fun <reified T : Any> getKClass(): KClass<T> = T::class
so I can then do
getKClass<List<Int>>()
and assign that to a variable to save
then they match
262 Views