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] <: 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.immutable.SortedMap("A" -> "1")
val mt = m.upd("A", "2")
val smt: collection.immutable.SortedMap[String, String] = sm.upd("A", "2")
println(mt)
println(smt)