Aren't == and `equals` synonyms in kotlin? ```data...
# getting-started
h
Aren't == and
equals
synonyms in kotlin?
Copy code
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
v
It is indeed, however, Kotlin here introduces a type check on a compiler level, unlike
equals
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 😅
h
But could I add a covariant(?) version of `equals`to allow comparing
Foo
against other types with
==
?
v
For comparison of
Foo
&
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.
j
It must be noted that
equals()
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.
âž• 2
h
Thanks for the clarification!
e
==
and
equals
are not exactly synonyms in some corner cases:
Copy code
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
although you can force the use of
equals
,
Copy code
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
==