Suma
Suma

Reputation: 34403

Implicit type class defined for Map not found for a SortedMap

In a following code (extracted from my attempt to extend Quicklens support to a SortedMap) the pimped upd is available for a Map, but not for a SortedMap.

Why - and how can I change the code so that UpdatedMap takes care of SortedMap (and other possible Map subclasses)?

object TImpl extends App {

  trait UpdatedTrait[A, K, T] {
    def upd(k: K, t: T): A
  }

  trait UpdatedFunctor[A, K, T] {
    def upd(a: A, k: K, t: T): A
  }

  implicit class UpdatedMap[M[KT, TT] <: Map[KT, TT], K, T](a: M[K, T])(implicit f: UpdatedFunctor[M[K, T], K, T]) {
    def upd(k: K, t: T) = {
      f.upd(a, k, t)
    }
  }

  implicit def mapUpdatedFunctor[M[KT, TT] <: Map[KT, TT], K, T] = new UpdatedFunctor[M[K, T], K, T] {
    override def upd(a: M[K, T], k: K, t: T): M[K, T] = {
      a.updated(k, t).asInstanceOf[M[K, T]]
    }
  }

  val m = Map("A" -> "1")
  val sm = collection.SortedMap("A" -> "1")

  val mt = m.upd("A", "2")
  val smt: collection.SortedMap[String, String] = sm.upd("A", "2")

  println(mt)
  println(smt)
}

Upvotes: 1

Views: 125

Answers (1)

Jatin
Jatin

Reputation: 31724

Simply because SortedMap extends scala.collection.Map.

Where as you have set a bound for M[KT, TT] <: scala.collection.immutable.Map[KT, TT]. Change both the bound's to scala.collection.Map and it works. Or probably you intended it to use scala.collection.immutable. SortedMap

If you wish it to run for all types of Map (i.e. mutable, immutable and collection), I am not sure if it is practical. Or probably with implicit conversions with a wrapper, but that would be ugly.

Upvotes: 2

Related Questions