Willis Blackburn Willis Blackburn - 1 year ago 99
Scala Question

Can I create a collection in Scala that uses different equals/hashCode/compare implementations?

I'm looking for as simple way to create an identity set. I just want to be able to keep track of whether or not I've "seen" a particular object while traversing a graph.

I can't use a regular Set because Set uses "==" (the equals method in Scala) to compare elements. What I want is a Set that uses "eq."

Is there any way to create a Set in Scala that uses some application-specified method for testing equality rather than calling equals on the set elements? I looked for some kind of "wrapEquals" method that I could override but did not find it.

I know that I could use Java's IdentityHashMap, but I'm looking for something more general-purpose.

Another idea I had was to just wrap each set element in another object that implements equals in terms of eq, but it's wasteful to generate tons of new objects just to get a new equals implementation.


Answer Source

This is a similar question. The accepted answer in that case was to use a TreeSet and provide a custom Comparator.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download