Charles-Eugene Loubao
Charles-Eugene Loubao

Reputation: 1100

Data Class Equality in Kotlin

Hello everyone I am trying to use the == to check if two variables are structurally equal

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

 }

Here the output I got

false
true

Why is it that the 2 variables are not equal in the first case and equal in the second case ?

THank you for clearing this up for me

Upvotes: 3

Views: 7060

Answers (1)

Cheng Chen
Cheng Chen

Reputation: 43523

Kotlin compiler generates hashCode and equals methods for data classes, including properties in the constructor only. The property name in PersonImpl1 is not included in the hashCode/equals, hence the difference. See the de-compiled code:

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

Upvotes: 14

Related Questions