https://kotlinlang.org logo
#getting-started
Title
# getting-started
r

RE

03/21/2022, 11:55 AM
I'm wrapping a DoubleArray with the value class, but when the values of the same content compare, it return false
s

Stephan Schroeder

03/21/2022, 3:36 PM
so the equals-method of DoubleArray is broken?? 🤔 (since value/inline classes simply delegate to the class they wrap )
Indeed
Copy code
fun main() {
    val d1 = DoubleArray(2){it.toDouble()}
    val d2 = DoubleArray(2){it.toDouble()}
    println(d1==d2)
}
prints
false
. https://pl.kotl.in/4W5_kBvI_
well, it's not a data class, so good old java reference equality is to be expected I guess.
r

Rob Elliot

03/21/2022, 3:48 PM
Arrays do identity equality on the JVM as I recall. You have to use
Arrays.equals
to compare them by their values.
s

Stephan Schroeder

03/21/2022, 3:59 PM
true, but to come back to the original question, it doesn't look like you can override the equals-method of value classes. I tried it here: https://pl.kotl.in/6gMuO7zh3 with
Copy code
@JvmInline
value class DAWrapper(
    val doubles: DoubleArray
) {
    override fun equals(other: Any?): Boolean {
        if(other !is DAWrapper) return false
        return Arrays.equals(doubles, other.doubles)
    }
}
and get the compile error
Member with the name 'equals' is reserved for future releases
looks like you have to use a data class for now
Copy code
data class DAWrapper(
    val doubles: DoubleArray
) {
    override fun equals(other: Any?) =
      other is DAWrapper &&
      Arrays.equals(doubles, other.doubles)
}
👍 1
k

Klitos Kyriacou

03/21/2022, 4:11 PM
4 Views