0

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?

Trylks
  • 1,458
  • 2
  • 18
  • 31
  • Also, is there any way to use the documentation in a better way so that I may not need to ask for such questions? Am I missing something? – Trylks Jun 11 '15 at 16:40
  • possible duplicate of [How can I define a custom equality operation that will be used by immutable Set comparison methods](http://stackoverflow.com/questions/7681183/how-can-i-define-a-custom-equality-operation-that-will-be-used-by-immutable-set) – marios Jun 11 '15 at 16:56

1 Answers1

4

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.

Daenyth
  • 35,856
  • 13
  • 85
  • 124
  • I see, and the documentation about `Set` and other specific classes says nothing because these methods should be (are) defined for *every class*, right? – Trylks Jun 11 '15 at 17:16
  • @Trylks They should be defined on every class which you ever intend to compare for equality or insert into a map or set. – Daenyth Jun 11 '15 at 17:17
  • Technically they already are, the compiler doesn't raise any errors. As far as I could see, it is impossible to not have them defined. – Trylks Jun 11 '15 at 18:02
  • They are implemented, but the implementation is often not useful. It's simply the object identity for equals (same instance), and for hashCode it uses the object's memory address. – Daenyth Jun 11 '15 at 18:24