2017-06-04 118 views
0

大家好,我試圖用==檢查兩個變量在結構上等於數據類平等科特林

// 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

你知道,你從來沒有設置'person2.name'或'person3.name'到什麼關係嗎? – tynn

回答

9

科特林編譯器生成hashCodeequals方法數據類,其中僅在構造函數的性質。 hashCode/equals中不包含namePersonImpl1,因此有差異。見去編譯代碼:

//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; 
    } 
+0

非常感謝。另外你如何看到Android Studio/IntelliJ中的反編譯的kotlin代碼? –

+1

@ Charles-EugeneLoubao我使用[JD GUI](http://jd.benow.ca/)將'class'文件反編譯爲java源代碼。 –

+1

您也可以在Android Studio中打開.kt文件,然後使用Tools - > Kotlin - > Show Kotlin Bytecode。在右側面板中將出現字節碼,也可以使用「反編譯」按鈕將其反編譯爲Java。 –