Grigorii Yurkov
04/11/2021, 4:52 PMequals
doc are not full?
Look at this code:
class MyClass {
override fun equals(other: Any?): Boolean {
return other != null
}
}
1. Reflexive: for any non-null value x, x.equals(x) should return true. ✅
2. Symmetric: for any non-null values x and y, x.equals(y) should return true if and only if y.equals(x) returns true.✅
3. Transitive: for any non-null values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.✅
4. Consistent: for any non-null values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.✅
5. Never equal to null: for any non-null value x, x.equals(null) should return false.✅
But this code leads to the strange behavior:
println(MyClass() == Any()) // true
println(Any() == MyClass()) // false
randomcat
04/11/2021, 4:53 PMrandomcat
04/11/2021, 4:54 PMx
and y
of any types, not just of the same typeGrigorii Yurkov
04/11/2021, 4:55 PMrandomcat
04/11/2021, 4:55 PMAny()
and MyClass()
Grigorii Yurkov
04/11/2021, 4:58 PMrandomcat
04/11/2021, 4:58 PMrandomcat
04/11/2021, 4:58 PMrandomcat
04/11/2021, 4:59 PMGrigorii Yurkov
04/11/2021, 5:02 PMGrigorii Yurkov
04/11/2021, 5:02 PMrandomcat
04/11/2021, 5:03 PMrandomcat
04/11/2021, 5:04 PMGrigorii Yurkov
04/11/2021, 5:21 PMrandomcat
04/11/2021, 5:25 PMGrigorii Yurkov
04/11/2021, 6:01 PMGrigorii Yurkov
04/11/2021, 6:05 PMVampire
04/11/2021, 6:26 PMVampire
04/11/2021, 6:26 PMVampire
04/11/2021, 6:28 PMx.equals(y)
should return true
if and only if y.equals(x)
returns true
.
And as Any().equals(MyClass())
will never return true
, your implementation must not return true
for MyClass().equals(Any())
or it would violate rule 2Vampire
04/11/2021, 6:31 PMtrue
for anything that is not of your exact same type (also not a sub- or sibling type) is wrong, except if some class adds to the rules for sub classes, so that e. g. all empty lists might be considered equal, independent from the implementation class.kqr
04/11/2021, 6:51 PMVampire
04/11/2021, 6:56 PMFleshgrinder
04/12/2021, 6:48 AM