I know with Kotlin (on the JVM) I can get the type of a class with foo::class
. And I know I can generic information, even at runtime, with typeOf<>()
(as long as my function is inline). But I can't figure out how to get Int
from a List<Int>
for example.
Here's as far as I can get:
import kotlin.reflect.KType
import kotlin.reflect.typeOf
fun main() {
TypeTest.get<Int>()
TypeTest.get<List<Int>>()
TypeTest.get<Map<String, List<Int>>>()
}
class TypeTest {
companion object {
@OptIn(ExperimentalStdlibApi::class)
inline fun <reified OUT : Any> get() {
generateReturnType(typeOf<OUT>())
}
fun generateReturnType(type: KType) {
val classifier = type.classifier!!
println("class $classifier has parameters ${classifier::class.typeParameters}")
}
}
}
This prints:
class class kotlin.Int has parameters [T]
class class kotlin.collections.List has parameters [T]
class class kotlin.collections.Map has parameters [T]
Given a KClassifier, how can I get its inner type (ideally recursively, in the case of a List<List<Int>>
)? Or is there another way to do this?
Aucun commentaire:
Enregistrer un commentaire