pathikrit
pathikrit

Reputation: 33459

Generically adding implicits to both TreeSet and TreeMaps

I want to add some helpful implicits to both mutable and immutable TreeMaps and TreeSets in Scala.

Here is my attempt:

  1. First try to define the least upper bound of TreeMap and TreeSet that has headOption/lastOption (from GenTraversableLike) and from/to/until (from Sorted):

      type SortedCollection[A, Repr <: SortedCollection[A, Repr]] = collection.generic.Sorted[A, Repr] with collection.GenTraversableLike[A, Repr]
    
  2. Write my util:

    implicit class RichSortedCollection[A, Repr <: SortedCollection[A, Repr]](s: SortedCollection[A, Repr]) {
      def greaterThanOrEqualTo(a: A): Option[A] = s.from(a).headOption
      def lessThan(a: A): Option[A] = s.until(a).lastOption
      def lessThanOrEqualTo(a: A): Option[A] = s.to(a).lastOption
    }
    

This only works partially: SortedSet#greaterThan compiles but TreeMap#greaterThan does not. How do I fix it?

Upvotes: 1

Views: 42

Answers (1)

Michael Zajac
Michael Zajac

Reputation: 55569

TreeMap[A, B] (transitively) extends GenTraversableLike[(A, B), TreeMap[A, B]] and Sorted[A, TreeMap[A, B]], so you could say it's a:

Sorted[A, TreeMap[A, B]] with GenTraversableLike[(A, B), TreeMap[A, B]]

This is close to your type alias, but the first type parameter of Sorted and GenTraverableLike in the type alias SortedCollection must be the same, which they are not above. They simply aren't compatible. That is, Repr = TreeMap[A, B] is fine, but A = (A, B) doesn't make sense.

You're going to have the same issue with all map types, and your only real choice is to re-implement RichSortedCollection for maps as well.

Upvotes: 1

Related Questions