https://kotlinlang.org logo
Title
b

bbaldino

01/10/2020, 8:58 PM
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

Milan Hruban

01/10/2020, 9:06 PM
these two give the same result
println(listOf<Int>().javaClass.kotlin)
println(listOf<Int>()::class)
b

bbaldino

01/10/2020, 9:07 PM
Ah, good catch, that's a bit better. I was hoping there was a way to avoid creating an instance though
m

Milan Hruban

01/10/2020, 9:10 PM
the generic type gets erased anyway right? Maybe you are just looking for
List::class
?
b

bbaldino

01/10/2020, 9:11 PM
That's actually what I'm playing with. In the KClass it's preserved
for example:
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: `
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