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

holgerbrandl

01/21/2022, 1:47 PM
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

Vlad Krava

01/21/2022, 1:56 PM
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

holgerbrandl

01/21/2022, 1:58 PM
But could I add a covariant(?) version of `equals`to allow comparing
Foo
against other types with
==
?
v

Vlad Krava

01/21/2022, 2:04 PM
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

Joffrey

01/21/2022, 2:15 PM
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

holgerbrandl

01/21/2022, 2:39 PM
Thanks for the clarification!
e

ephemient

01/21/2022, 9:53 PM
==
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
==
2 Views