Joffrey
05/16/2019, 1:13 PM==
is less permissive than its method counterpart equals()
?
The compiler doesn't seem to accept 'c' == "string"
, but it does accept 'c'.equals("string")
.
Isn't it supposed to be the same code? In IntelliJ IDEA, when Ctrl+clicking ==
, it brings me to the same definition as `equals()`:
public open operator fun equals(other: Any?): Boolean
This is supposed to accept Any?
. Did the Kotlin team keep this equals()
signature for easier Java interop? In this case, is the inconsistency with ==
intended in order to provide more type safety?Czar
05/16/2019, 1:20 PM==
is not the same as equals
, like for instance in your example. ==
is an operator whose implementation usually follows `equals`' semantics, but when safety is concerned it may be missing altogether.Jonathan Mew
05/16/2019, 1:21 PMCharacter
instance at which point the .equals method is available.
Just a guess though.
@Czar could you expand on the safety thing?Czar
05/16/2019, 1:22 PM==
.Joffrey
05/16/2019, 1:22 PMequals()
, and this one compiles fine.Czar
05/16/2019, 1:22 PMequals
has to remain.Joffrey
05/16/2019, 1:23 PMJoffrey
05/16/2019, 1:27 PMclass X {
override operator fun equals(other: Any?): Boolean {
return true;
}
}
Jonathan Mew
05/16/2019, 1:28 PMJonathan Mew
05/16/2019, 1:29 PMx = X()
x == "something"
x.equals("something")
And it complains about x == "something"Joffrey
05/16/2019, 1:30 PM==
is not the same as `equals`". Then I may have misunderstood operator overloading in Kotlin. Could you please expand on this? I though declaring plus
, equals
, compareTo
etc in a class was the way to define how operators +
, ==
and >
and the likes worked for that class.Jonathan Mew
05/16/2019, 1:31 PMJoffrey
05/16/2019, 1:32 PM==
does not compile, while equals()
does.Jonathan Mew
05/16/2019, 1:32 PMJoffrey
05/16/2019, 1:36 PMequals
semantics"? In the documentation, it says that the usage of operators is "translated to" the methods. Isn't it the case? Or are some shortcuts made for well-known types like Char
?Czar
05/16/2019, 1:36 PM'' == ""
does not compile.Joffrey
05/16/2019, 1:37 PMCzar
05/16/2019, 1:38 PMJoffrey
05/16/2019, 1:45 PMJonathan Mew
05/16/2019, 2:04 PMJonathan Mew
05/16/2019, 2:05 PMPavlo Liapota
05/16/2019, 2:53 PM.equals()
and ==
π
- it is safe to compare nullable variables with ==
, for ex. nullable1 == nullable2
, it will not be transformed directly to nullable1.equals(nullable2)
- if you compare primitives with ==
, then .equal()
is not called at allJoffrey
05/16/2019, 7:13 PM