Implicit type class for updating maps With the help of SO I got my code working, but I think it still could be improved, in particular I do not like using asInstanceOf. Is there some way how to avoid it?

  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] &lt;: 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] &lt;: 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" -&gt; "1")
  val sm = collection.immutable.SortedMap("A" -&gt; "1")

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

  println(mt)
  println(smt)
Using CanBuildFrom will help you here. What you need is an implicit CanBuildFrom[M[K, T], (K, T), M[K, T]] in scope, which will be provided by the standard library if it is possible to construct instances of the correct types.

import scala.collection.generic.CanBuildFrom

implicit def mapUpdatedFunctor[M[KT, TT] &lt;: Map[KT, TT], K, T]
  (implicit cbf: CanBuildFrom[M[K, T], (K, T), M[K, T]]) = {
  new UpdatedFunctor[M[K, T], K, T] {
    override def upd(a: M[K, T], k: K, t: T): M[K, T] = {
      val builder = cbf()
      builder ++= a.updated(k, t)
      builder.result()
    }
  }
}

scala&gt; m.upd("A", "2")
res1: scala.collection.immutable.Map[String,String] = Map(A -&gt; 2)

scala&gt; sm.upd("A", "2")
res3: scala.collection.immutable.SortedMap[String,String] = Map(A -&gt; 2)


I actually answered a similar question recently using Maps and updated on SO.