Mark
05/23/2020, 1:34 AMShawn
05/23/2020, 2:10 AMequals
and hashCode
in the interface, have an internal abstract class implement the interface, have implementing classes implement the interface via delegation
import java.util.Objects
interface Foo {
val a: Int
val b: Int
val c: Int
override fun equals(other: Any?): Boolean
override fun hashCode(): Int
}
internal abstract class AbstractFoo(
override val a: Int,
override val b: Int,
override val c: Int) : Foo {
override fun equals(other: Any?): Boolean {
print("wow! ")
return other is Foo && other.a == a && other.b == b
}
override fun hashCode(): Int = Objects.hash(a, b)
}
class BarFoo : Foo by object : AbstractFoo(1,2,3) {}
class BazFoo : Foo by object : AbstractFoo(1,2,4) {}
val barFoo: Foo = BarFoo() // not sure why one needs to be annotated as Foo
val bazFoo = BazFoo()
println(barFoo == bazFoo) // prints "wow! true"
Shawn
05/23/2020, 2:11 AMMark
05/23/2020, 2:27 AMfun MyInterface.hashCode() =…
and then in each class have something like override fun hashCode() = defaultHashCode()
Mark
05/23/2020, 2:28 AM