我需要将字符串映射到函数。我尝试了以下方法:
def a(a: Int,..) = ...
它表示具有各种参数的通用函数,
然后
val m: Map[String, Funcs] = Map("a"-> a)
在哪里
type Funcs = (Any*) => Any
但它并没有真正起作用..我想制作以字符串为键的混合函数映射。
最佳答案
这并不容易。事实上,在运行时几乎不可能做到这一点。在编译时,您可以使用一些技巧,所有这些技巧都可以在库 Shapeless 中找到。 .您不必将 Shapeless 用作 Miles showed in a gist他解释说:
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 }
现在在编译时你可以匹配你需要的所有不同的东西
implicit def fAssoc = mkAssoc("f", f)
implicit def gAssoc = mkAssoc("g", g)
并将它们检索为
def lookup(k: String)(implicit assoc: Assoc[k.type]): assoc.V = assoc.value
如果你像他用他的 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
并创建一个类,例如
class Mapped extends FMapper{
implicit val f = mkAssoc("f", f)
implicit val g = mkAssoc("g", g)
但正如你所看到的,它开始变得越来越难看......
关于scala - 在 Scala 中创建映射字符串 -> 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25058699/