Are Kotlin's reified types incorrect for primitives on the JVM?

跟風遠走 提交于 2019-12-05 02:14:07

This is somewhat confusing, but the current behavior is by design. This approach has a major benefit compared to the one where we would treat T::class.java as a primitive class. If the function has a parameter of type T, its Java class is always equal to T::class.java at runtime (assuming T is final). This is actually a very sensible thing to expect:

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

This happens because the parameter of a generic type T can only have a reference value at runtime, which is necessarily a boxed value if T is a primitive type.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!