Create Map Line & # 8594; Function in Scala

I will need to map strings to functions. I tried the following:

def a(a: Int,..) = ... 

which is a common function with various arguments,

then

 val m: Map[String, Funcs] = Map("a"-> a) 

Where

  type Funcs = (Any*) => Any 

but it really does not work. I would like to make maps of mixed functions with a string as a key.

+6
source share
1 answer

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 ...

+2
source

Source: https://habr.com/ru/post/973164/


All Articles