androidkotlinkotlin-sealed

Sealed data classes not considering parent property in equals


Consider the following:

sealed class MySealedClass(val guid: String = UUID.randomUUID().toString()) {
    data class MyDataClass(var title: String) : MySealedClass()
    data class MyDataClass2(var something: String) : MySealedClass()
}

val instance1 = MySealedClass.MyDataClass("hello")
val instance2 = MySealedClass.MyDataClass("hello")

Timber.i("instance1 guid: ${instance1.guid}")
Timber.i("instance2 guid: ${instance2.guid}")
Timber.i("are instances equal? ${instance1 == instance2}")

// Output:
instance1 guid: <removed>eb
instance2 guid: <removed>a6 // note that instance 2 GUID is different!
are instances equal? true   // yet the instances are considered equal

Seems like the guid property from the parent class MySealedClass is not considered in the equals() method generated for the data classes. How can I make sure that it is considered? Is there any way without touching the generated equals() method?


Solution

  • Data classes in Kotlin use only properties listed in the primary constructor, when equals/hashCode/toString generated (see documentation). So, to include the guid into generated methods implementation, pass it as a constructor parameter:

    data class MyDataClass(
        var title: String, 
        override val guid: String = UUID.randomUUID().toString()
    ) : MySealedClass()