我需要将字符串映射到函数.我尝试了以下方法:
def a(a: Int,..) = ...
Run Code Online (Sandbox Code Playgroud)
表示具有各种参数的泛型函数,
然后
val m: Map[String, Funcs] = Map("a"-> a)
Run Code Online (Sandbox Code Playgroud)
哪里
type Funcs = (Any*) => Any
Run Code Online (Sandbox Code Playgroud)
但它确实不起作用..我想用字符串作为键来制作混合函数的映射.
这并不容易。事实上,在运行时几乎不可能做到这一点。在编译时,您可以使用多种技巧,所有这些技巧都可以在Shapeless库中找到。你不必像迈尔斯在要点中所展示的那样使用 Shapeless ,他解释说:
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 }
Run Code Online (Sandbox Code Playgroud)
现在在编译时你可以匹配你需要的所有不同的东西
implicit def fAssoc = mkAssoc("f", f)
implicit def gAssoc = mkAssoc("g", g)
Run Code Online (Sandbox Code Playgroud)
并将它们检索为
def lookup(k: String)(implicit assoc: Assoc[k.type]): assoc.V = assoc.value
Run Code Online (Sandbox Code Playgroud)
如果你将这些推入一个类中,就像他处理 HMap 一样,你可以按照 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
Run Code Online (Sandbox Code Playgroud)
并创建一个类,例如
class Mapped extends FMapper{
implicit val f = mkAssoc("f", f)
implicit val g = mkAssoc("g", g)
Run Code Online (Sandbox Code Playgroud)
但正如你所看到的,它很快就开始变得丑陋......