I wonder why the equal method (==) does not work as expected.
Is there any way to fix the commented section in the code below?
As you can see p1 and p2 are not equals, neither reference nor value. So why p1 == p2 is true?!
object Main {
@JvmStatic
fun main(args: Array<String>) {
val f1 = Foo(1)
Thread.sleep(3) // to set a different value in parent of f2
val f2 = Foo(1)
val p1 = (f1 as Parent)
val p2 = (f2 as Parent)
println(p1 == p2) // true
println(p1.b == p2.b) // false
}
}
data class Foo(val a: Int) : Parent("$a-${System.currentTimeMillis()}")
sealed class Parent(val b: String) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Parent
if (b != other.b) return false
return true
}
override fun hashCode(): Int {
return b.hashCode()
}
}