Define equality/ordering implicitly for collections

82 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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(...)