I have a map of KClass
to Int
. I then have a function which has a reified generic type. I'd then expect the following situation, thus, to give me the Int
associated with Boolean::class
val kclassToInt = mapOf(Boolean::class to 1, Byte::class to 1, Short::class to 2)
inline fun <reified T> myExpectations() =
assertEquals(1, kclassToInt.getRaw(T::class), "Why doesn't it work? :'(")
I'm greeted with Why doesn't it work? :'(. Expected <1>, actual <null>.
from a call to it like this myExpectations<Boolean>()
.
I then tried to use .java
off, so I was using Java's Class
rather than Kotlin's KClass
.
val classToInt = mapOf(Boolean::class.java to 1, Byte::class.java to 1, Short::class.java to 2)
inline fun <reified T : Any> anotherExpectation() =
assertEquals(1, classToInt.getRaw(T::class.java))
This time I was again greeted by assertion error: java.lang.AssertionError: Expected <1>, actual <null>.
Finally I tried using .javaClass
rather than .java
:
val javaClassToInt = mapOf(Boolean::class.javaClass to 1, Byte::class.javaClass to 1, Short::class.javaClass to 2)
inline fun <reified T> pleaseWork() =
assertEquals(1, javaClassToInt.getRaw(T::class.javaClass))
This time it was really strange. I was greeted with this: java.lang.AssertionError: Expected <1>, actual <2>.
This seems to be because all .javaClass
refer to KClassImpl
.
Finally I resorted to what I didn't want to do, use .qualifiedName
:
val qnToInt = mapOf(Boolean::class.qualifiedName to 1, Byte::class.qualifiedName to 1, Short::class.qualifiedName to 2)
inline fun <reified T> iKnowItWorks() =
assertEquals(1, qnToInt.getRaw(T::class.qualifiedName))
Which of course works and is what I use in my actual use case: https://github.com/Jire/kotmem/blob/master/src/main/kotlin/org/jire/kotmem/Process.kt