Kotlin中的数据类平等

时间:2017-06-04 02:06:03

标签: kotlin

大家好我试图使用==检查两个变量是否在结构上相等

// PersonImpl0 has the name variable in the primary constructor
data class PersonImpl0(val id: Long, var name: String="") {
}

// PersonImpl1 has the name variable in the body
data class PersonImpl1(val id: Long) {
     var name: String=""
}

fun main(args: Array<String>) {
    val person0 = PersonImpl0(0)
    person0.name = "Charles"

    val person1 = PersonImpl0(0)
    person1.name = "Eugene"

     val person2 = PersonImpl1(0)
    person0.name = "Charles"

    val person3 = PersonImpl1(0)
    person1.name = "Eugene"

    println(person0 == person1) // Are not equal ??
    println(person2 == person3) // Are equal ??

 }

这是我得到的输出

false
true

为什么2个变量在第一种情况下不相等而在第二种情况下相等?

感谢你为我清理这件事

1 个答案:

答案 0 :(得分:9)

Kotlin编译器为数据类生成hashCodeequals方法,仅包括构造函数中的属性。 name PersonImpl1中的hashCode属性未包含在equals / //hashcode implementation of PersonImpl1 public int hashCode() { long tmp4_1 = this.id; return (int)(tmp4_1 ^ tmp4_1 >>> 32); } //equals implementation of PersonImpl1 public boolean equals(Object paramObject) { if (this != paramObject) { if ((paramObject instanceof PersonImpl1)) { PersonImpl1 localPersonImpl1 = (PersonImpl1)paramObject; if ((this.id == localPersonImpl1.id ? 1 : 0) == 0) {} } } else { return true; } return false; } 中,因此存在差异。请参阅解压缩代码:

{{1}}