Kotlin 密封类和 hashcode/equals

ivm*_*mos 3 equals hashcode kotlin sealed-class

我正在编写一个测试,我无法断言两个具有相同“子类”和底层相同值的密封类是相等的。它们是截然不同的。

fun main() {

    val a1 = MySealed.A("foo")
    val a2 = MySealed.A("foo")

    System.out.println(a1 == a2)
    
    val a3 = MySealedWithEqualsAndHashCodeOverriden.A("foo")
    val a4 = MySealedWithEqualsAndHashCodeOverriden.A("foo")
    
    System.out.println(a3 == a4)
    
}

sealed class MySealed(val value: String) {
    class A(value: String) : MySealed(value)
}

sealed class MySealedWithEqualsAndHashCodeOverriden(val value: String) {
    class A(value: String) : MySealedWithEqualsAndHashCodeOverriden(value) {
         override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (javaClass != other?.javaClass) return false
            return true
        }

        override fun hashCode(): Int {
            return javaClass.hashCode()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

该主函数返回:

false
true
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么会有这种行为。我想这与密封类本身的性质有关,但我不明白?

提前致谢

Joã*_*ias 7

Kotlin Sealed 类不会覆盖Java 类equals()的默认实现Object。这意味着对象是使用它们的引用进行比较的,因此a1a2不相等。

Kotlin 数据类会equals()根据主构造函数中声明的所有属性来重写该方法(有关它们的更多信息,请访问https://kotlinlang.org/docs/data-classes.html)。