Scala set element uniqueness: What to implement for comparison of user defined classes?

609 views Asked by At

I am trying to find this information in the Scala documentation but it looks like it is not there.

In the case of Java this was dependent of the Set implementation that was used, AFAIK. In some cases the method to implement was equals, in the case of a HashSet the comparison was done with the hash method.

The actual implementation details of scala.collections.mutable.Set seem to be unspecified, as the implementation may vary (and that's nice, I like my code to be generic), but I wonder how can I ensure specific comparisons are done with such a generic collection.

For example, in the case of SortedSet there is an implicit Ordering[A] to ensure the order. Is there anything similar in the case of Set?

1

There are 1 answers

4
Daenyth On BEST ANSWER

Both scala and java require you to implement both equals and hashCode in a consistent way. If it worked with just one in some cases it's coincidental. You must have both so that with your class being X, for every X, x1.equals(x2) == (x1.hashCode() == x2.hashCode()).

Scala case classes have equals and hashCode methods implemented by the compiler for you.