Why does the following code return true for Float ...
# kotlin-native
m
Why does the following code return true for Float comparison and false in some cases for objects?
Copy code
data class B(val a: Float, val b: Float)

data class A(val a: Float, val b: Float) {
    override fun equals(other: Any?): Boolean {
        if(other is A) {
            return a == other.a && b == other.b
        }
        return false
    }
}

fun main(args: Array<String>) {
    println(0.0f == -0.0f) // true
    println(B(0.0f, 0.0f) == B(0.0f, -0.0f)) // false
    println(B(2f, 4f) == B(2f, 4f)) // true
    println(A(0.0f, 0.0f) == A(0.0f, -0.0f)) // true (workaround)
}
This look like a bug for me as the generated
equals()
for the data class is returning false for comparison that otherwise returns (and should return) true.
Also I am using
id 'kotlin-multiplatform' version '1.3.11'
o
This is intentional behavior, and matches one on JVM, see
equals
section in https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html
m
So are the
a
,
b
properties represented as boxed types and not primitives? Or the `equals`and
hashCode
are implemented in a way that even non-boxed types are considered as "boxed" during to comparison?
o
nope, just members compared with
equals
, for example
println(0.0f.equals(-0.0f))
prints
false
👍 1
u
Why does the workaround return true then?
o
Because it overrides comparison
u
But it uses float comparison under the hood, right?
And you say
println(0.0f.equals(-0.0f))
prints
false
o
equals
and
==
is not the same operation for floats
u
Got it. Thanks
👍 1