Hello all, I am trying to figure out the best way ...
# getting-started
b
Hello all, I am trying to figure out the best way to include a data classes inherited fields in hashCode and equals methods. Code in thread
Copy code
open class Foo(
   var foo: String? = null
)
Copy code
data class Bar(
   val bar: String,
): Bookmark() {
   // implement my hashCode and equals to account for bar and foo fields.
}
Since a data class does not include inherited fields in hashCode and equals I will need to provide my own implementation. I did try to implement hashCode and equals in Foo, but that doesn’t help either with inheritance. If there are a lot of fields in Bar, this leads to a lot of “boilerplate” code. Is there a way to take advantage of Bars already implemented hashCode and equals methods? Possibly this for equals using ‘===’?
Copy code
override fun equals(other: Any?): Boolean {
   return  (other is Bar) &&
           this === other &&
           foo == other.foo
}
j
One simpler option is to override the property in your data class constructor:
Copy code
kotlin
data class Bar(
    val bar: String,
    override val foo: String? = null,
) : Foo()
1
👏 1
p
https://pl.kotl.in/RJoah-tNj overriding in the constructor is the only way to take advantage of the
data class
at all, really
b
Thank you both, makes a ton of sense and was not at all obvious to me at first thought.
k
How about
Copy code
data class Bar(val bar: String, val foo: Foo): Foo by foo
j
It depends on the semantics of the different parts, but yes that's also a good option
btw I'm not sure you can extend a class by delegation like this, it would probably require to turn
Foo
into an interface first
1