Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin - KClass<*> from KType

In Kotlin, I can obtain a KType from a KClass<*> like so:

Int::class.createType()

kotlin.Int

How do I do the reverse and obtain the KClass<Int> from a KType representing a kotlin.Int?

like image 266
Matthew Layton Avatar asked Jun 20 '19 12:06

Matthew Layton


1 Answers

You can use KType.classifier for this:

val intType : KType = Int::class.createType()
val intClassifier : KClassifier? = intType.classifier
assertEquals(Int::class, intClassifier) // true

Note that since 1.3.40 you can also (at least on the JVM) use the experimental typeOf<Int>() to get your KType. You may want to have a look at the 1.3.40-announcement to see whether that might be useful to you.

Speaking of the JVM: on the JVM you can also use KType.jvmErasure to get the actual class as also marstran pointed out in the comment.

like image 154
Roland Avatar answered Oct 18 '22 23:10

Roland