Are the wrong Kotlin types invalid for JVM primitives?

If the call to the Kotlin function confirms the primitive, say Int , the 'pass' class is that of the boxed primitive, not the unboxed version.

 inline fun <reified T> reify() = T::class @Test fun reified_type_doesnt_match_for_primitive() { assertNotEquals(Int::class, reify<Int>()) assertNotEquals(Int::class.java, reify<Int>().java) assertNotEquals<Any>(Int::class, reify<Int?>()) val nullableInt: Int? = 42 assertNotEquals(nullableInt!!.javaClass.kotlin, reify<Int>()) assertEquals<Any>(java.lang.Integer::class.java, reify<Int>().java) } @Test fun reified_type_matches_for_class() { assertEquals(String::class, reify<String>()) } 

This is mistake?

+7
jvm-languages kotlin
source share
1 answer

This is somewhat confusing, but the current design behavior. This approach has a big advantage compared to where we will consider T::class.java as a primitive class. If a function has a parameter of type T , its Java class is always equal to T::class.java at run time (provided that T is final). This is actually a very reasonable thing:

  inline fun <reified T : Any> foo(t: T) { assert(T::class.java == t.javaClass) } 

This is because a parameter of the universal type T can only have a reference value at run time, which is necessarily a unit value if T primitive type.

Also see the topic on the Kotlin forum on this topic: https://devnet.jetbrains.com/thread/475540

+9
source share

All Articles