How do you override the equals operator so that you can apply it to sibling classes? I always get Operator '==' cannot be applied to 'Length.Kilometer' and 'Length.Meter' in the below example.
Kotlin Playground: https://pl.kotl.in/uT4Ch5mem
Copy code
abstract class Length {
abstract val meters: Double
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Length) return false
return meters.equals(other.meters)
}
override fun hashCode() = meters.hashCode()
class Meter(value: Double) : Length() {
override val meters: Double = value
}
class Kilometer(value: Double) : Length() {
override val meters: Double = value * 1000.0
}
}
fun main() {
val oneKm = Length.Kilometer(1.0)
val oneThousandMeters = Length.Meter(1000.0)
println(oneKm.equals(oneThousandMeters))
// true
println(oneKm as Length == oneThousandMeters as Length)
// true
println(oneKm == oneThousandMeters)
// this will not compile: Operator '==' cannot be applied to 'Length.Kilometer' and 'Length.Meter'
}