Sorry if this is obvious but I just realized I wasn’t sure — is equality in a
Set
compared via
equals()
?
g
Grégory Lureau
10/04/2021, 2:22 PM
Afaik HashSet/HashMap first check with hashCode() then, if hashCodes are similar, use equals()
👍 1
j
Joffrey
10/04/2021, 3:38 PM
The Java definition of the
Set
interface defines equality using
equals()
, but the Kotlin definition is lousy here (honestly most of Kotlin's stdlib KDoc is really less precise than the Java counterpart, potentially because it could vary across platforms).
So technically in Kotlin it depends on the `Set`'s implementation, but it's a pretty safe bet to say that equality should be based on
equals()
in most implementations (at least on the JVM). The most common one (
a couple exceptions I just remembered: java.util.IdentityHashMap does break the contract that keys use
equals
, because it uses object identity instead. also SortedSet/SortedMap can be inconsistent with equals depending on the implementation of Comparable.compareTo or Comparator.compare. but the point stands that sets and map keys are generally expected to compare by equals