mariosangiorgio
mariosangiorgio

Reputation: 5543

Call distinct on an immutable list with a custom equality relation in Scala

I'd like to extract the distinct elements from a Scala list, but I don't want to use the natural equality relation. How can I specify it?

Do I have to rewrite the function or is there any way (maybe using some implicit definition that I am missing) to invoke the distinct method with a custom equality relation?

Upvotes: 5

Views: 938

Answers (1)

kiritsuku
kiritsuku

Reputation: 53348

distinct does not expect an ordering algorithm - it uses the equals-method (source).

One way to achieve what you want is to create your own ordering and pass it to a SortedSet, which expects an Ordering:

implicit val ord = new Ordering[Int] {
  def compare(i: Int, j: Int) = /* your implementation here */
}
val sortedList = collection.immutable.SortedSet(list: _*)/*(ord)*/.toList

Upvotes: 8

Related Questions