0

Is it possible to define my own notion of equality or ordering for the collections in Scala? Overriding equals and hashCode doesn't work in this case because I'd like to have more than one instance.

Here is roughly what I had in mind: (ignore the invalidity of this code)

implicit val customEq1(x: Int, y: Int) = x % 8 == y % 8
val customEq2(x: Int, y: Int) = x.toString == y.toString.take(2)

val union = Set(1,15,3).union(Set(3,7,8)) // => Set(1,3,8)

I'd imagine equality/ordering being a typeclass, but the functions like e.g. diff, union, intersect don't seem to offer any such functionality.

TomTom
  • 2,820
  • 4
  • 28
  • 46
  • 1
    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) – DeadNight Jan 03 '17 at 09:01
  • The answers to the "duplicate" question suggest overriding `equals` which is not what I wanted, as explained in my question. – TomTom Jan 03 '17 at 13:29

1 Answers1

-1

If you have multiple different implementations for comparison, you can create a class for each with the appropriate overrides, then coerce the type of the set with implicit conversion, something like this:

class MyCompInt { overrides... }
val union = Set[MyCompInt](1, 15, 3).union(...)
DeadNight
  • 55
  • 9