Data Class Equality in Kotlin

Viewed 5660

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

1 Answers
Related