Lack of Kotlin Equality

The following snippet shows the result of checking the equality of Kotlin links KClassreceived from different sources. Their string representations are the same. But their Java classes are different. It is expected that c, c0and c1are equal. But for some reason this is not the case.

Is there any nuance or is this a mistake? If this is not a mistake, then what is a reliable way to check the equality of KClasses?

fun main(args: Array<String>) {
    val c = Int::class
    fun test(v0: Any, v1: Any) {
        val c0 = v0.javaClass.kotlin
        val c1 = v1.javaClass.kotlin
        println("c= $c;  c0= $c0;  c1= $c1") // c= class kotlin.Int;  c0= class kotlin.Int;  c1= class kotlin.Int
        println("c= ${c.java};  c0= ${c0.java};  c1= ${c1.java}") // c= int;  c0= class java.lang.Integer;  c1= class java.lang.Integer
        println("c = c0? ${c == c0};  c0 = c1? ${c1 == c0}") // c = c0? false;  c0 = c1? true
    }
    test(11, 22)
}

EDIT:

The workaround is to use the method KClass.javaObjectType.

The docs say:

Returns an instance of the Java class corresponding to this instance of KClass. In the case of primitive types, it returns the corresponding wrapper classes.

those. c.javaObjectType == c1.javaObjectTypetruly

, KClass es, , . , . .

+4
1

, KClass es , Java, Kotlin. int java.lang.Integer.

KClass javaObjectType, Java ( ) Kotlin, Java:

 fun sameClass(c1: KClass<*>, c2: KClass<*>) = c1.javaObjectType == c2.javaObjectType

 sameClass(Int::class, (1 as Any?)!!.javaClass.kotlin) //true

, , .

, KClass Kotlin, , Kotlin, KType, .


UPD: , KClass.equals KDoc 1.0.2.

+3

All Articles