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 

为什么这两个变量在第一种情况下不相等,在第二种情况下是相等的呢?

谢谢你为我清理这个

Kotlin编译器生成hashCodeequals数据类的方法,包括仅在构造函数中的属性。 PersonImpl1的属性name不包含在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; }