holgerbrandl
01/21/2022, 1:47 PMequals
synonyms in kotlin?
data class Foo(val value: Double)
Foo(3.0) == 3.0 // fails to compile with "Operator '==' cannot be applied to 'Foo' and 'Double'"
Foo(3.0).equals(3) // compiles
Vlad Krava
01/21/2022, 1:56 PMequals
method (function), which needs to do this when overriding it according to best practices
Think of this behaviour as like a safeguard against naughty developers 😅holgerbrandl
01/21/2022, 1:58 PMFoo
against other types with ==
?Vlad Krava
01/21/2022, 2:04 PMFoo
& Boo
let’s say better use your custom function (not equals
though but some sort of equivalent
) Leave ==
and equals
for equality-check of the same time.Joffrey
01/21/2022, 2:15 PMequals()
has to be symmetric by contract. If Foo(3.0).equals(3.0)
is true, then 3.0.equals(Foo(3.0))
should be true too. But, since you can't override Double.equals()
, 3.0.equals(Foo(3.0))
will be false. So, your Foo.equals()
is technically broken if you accept Double
there.
So I agree with Vlad, you should probably use your own custom method for it.holgerbrandl
01/21/2022, 2:39 PMephemient
01/21/2022, 9:53 PM==
and equals
are not exactly synonyms in some corner cases:
Double.NaN == Double.NaN // false, as defined by IEEE 754
Double.NaN.equals(Double.NaN) // true
0.0 == -0.0 // true, as defined by IEEE 754
0.0.equals(-0.0) // false
equals
,
Double.NaN as Any == Double.NaN // true
0.0 as Any == -0.0 // false
showing that this is really due to Double trying to maintain consistency between .hashCode()
and .equals()
, which necessarily breaks consistency between boxed .equals()
and primitive ==