It is not simple. Actually it is almost impossible at runtime. There are several tricks that you can use during compilation, all of which are found in the Shapeless library. You do not need to use Shapeless as Miles, shown in the entity in which he explained:
trait Assoc[K] { type V ; val value: V } def mkAssoc[V0](k: String, v: V0): Assoc[k.type] { type V = V0 } = new Assoc[k.type]{ type V = V0 }
and now during compilation you can match all the things you need.
implicit def fAssoc = mkAssoc("f", f) implicit def gAssoc = mkAssoc("g", g)
and get them like
def lookup(k: String)(implicit assoc: Assoc[k.type]): assoc.V = assoc.value
if you push them to a class, as it did with its HMap, you could do something along the lines of Poly1:
abstract class FMapper{ protected def mkAssoc[V0](k: String, v: V0): Assoc[k.type] { type V = V0 } = new Assoc[k.type]{ type V = V0 } def apply(k: String)(implicit assoc: Assoc[k.type]): assoc.V = assoc.value
and create a class like
class Mapped extends FMapper{ implicit val f = mkAssoc("f", f) implicit val g = mkAssoc("g", g)
but, as you can see, it starts quickly ugly ...
source share