数据类平等科特林
大家好,我试图用==
检查两个变量在结构上等于数据类平等科特林
// 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的输出第一种情况下变量不相等,第二种情况下变量相等?
感谢您清除此为我
科特林编译器生成hashCode
和equals
方法数据类,其中仅在构造函数的性质。 hashCode
/equals
中不包含name
PersonImpl1
,因此有差异。见去编译代码:
//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;
}
非常感谢。另外你如何看到Android Studio/IntelliJ中的反编译的kotlin代码? –
@ Charles-EugeneLoubao我使用[JD GUI](http://jd.benow.ca/)将'class'文件反编译为java源代码。 –
您也可以在Android Studio中打开.kt文件,然后使用Tools - > Kotlin - > Show Kotlin Bytecode。在右侧面板中将出现字节码,也可以使用“反编译”按钮将其反编译为Java。 –
你知道,你从来没有设置'person2.name'或'person3.name'到什么关系吗? – tynn