Idea suggests to simplify `0f == (-0f)` as `false`...
# intellij
e
Idea suggests to simplify
0f == (-0f)
as
false
, which is wrong
d
Copy code
Although negative zero and positive zero are generally considered equal for comparison purposes, some programming language relational operators and similar constructs treat them as distinct. According to the Java Language Specification,[5] comparison and equality operators treat them as equal, but Math.min() and Math.max() distinguish them (officially starting with Java version 1.1 but actually with 1.1.1), as do the comparison methods equals(), compareTo() and even compare() of classes Float and Double
k
Doesn't matter, the IDE shouldn't suggest replacing any expression that returns
true
with
false
.
d
oh that's interesting, because I assumed it returns false, given Java spec, and OPs confusion was for different reasons
k
Well your quote says:
According to the Java Language Specification,[5] comparison and equality operators treat them as equal
d
Copy code
but Math.min() and Math.max() distinguish them (officially starting with Java version 1.1 but actually with 1.1.1), as do the comparison methods equals(), compareTo() and even compare() of classes Float and Double
maybe I am reading it wrong
k
They are equal according to
==
, but not according to
Float.equals
.
👍 1
From the
java.lang.Float.equals
docs:
If f1 represents +0.0f while f2 represents -0.0f, or vice versa, the equal test has the value false, even though 0.0f==-0.0f has the value true.
d
I thought == is operator for equals()
k
Not really it turns out:
Copy code
val posPrimitive: Float = 0.0f
val negPrimitive: Float = -0.0f

val posBoxed: Float? = posPrimitive
val negBoxed: Float? = negPrimitive

println(posPrimitive == negPrimitive)   //true
println(posBoxed == negBoxed)           //true
println(posBoxed?.equals(negBoxed))     //false
Now I'm confused myself, I would have expected
true, false, true
.
d
Copy code
println(posPrimitive.equals(negPrimitive))   //false
k
That boxes the primitives and calls the actual
Float.equals
function, so according to the docs that makes sense.
e
So, I managed to get Karel confused.. excellent ^^
😄 1
k
Turns out there literally is a special case for floats in the compiler: https://kotlinlang.org/docs/reference/equality.html#floating-point-numbers-equality
👍 1
Why is this not a Kotlin puzzler yet?
🧌 2