在Scala中定义从字符串到函数的映射

我试图用key定义一个Map文字:String,value:(Any)=> String.我尝试以下,但是得到一个语法错误

def foo(x: Int): String = /...
def bar(x: Boolean): String = /...
val m = Map[String,(Any) => String]("hello" -> foo,"goodbye" -> bar)

解决方法

有趣的是,没有人实际上给了一种可以工作的类型.这是一个

def foo(x: Int): String = x.toString
def bar(x: Boolean): String = x.toString
val m = Map[String,(nothing) => String]("hello" -> foo,"goodbye" -> bar)

这样做的原因是因为Function1在输入上是反变体的,所以(nothing)=> String是(Int)=>的超类串.它也是输出上的变体,所以(nothing)=>任何一个都将是任何其他Function1的超类.

当然,你不能这样使用它.没有清单,你甚至不能发现什么是原始类型的Function1.你可以尝试这样的东西:

def f[T : Manifest](v: T) = v -> manifest[T]
val m = Map[String,((nothing) => String,Manifest[_])]("hello" -> f(foo),"goodbye" -> f(bar))

val IntManifest = manifest[Int]
val BooleanManifest = manifest[Boolean]
val StringManifest = manifest[String]
m("hello")._2.typeArguments match {
    case List(IntManifest,StringManifest) =>
        m("hello")._1.asInstanceOf[(Int) => String](5)
    case List(BooleanManifest,StringManifest) =>
        m("hello")._1.asInstanceOf[(Boolean) => String](true)
    case _ => "UnkNown function type"
}

相关文章

共收录Twitter的14款开源软件,第1页Twitter的Emoji表情 Tw...
Java和Scala中关于==的区别Java:==比较两个变量本身的值,即...
本篇内容主要讲解“Scala怎么使用”,感兴趣的朋友不妨来看看...
这篇文章主要介绍“Scala是一种什么语言”,在日常操作中,相...
这篇文章主要介绍“Scala Trait怎么使用”,在日常操作中,相...
这篇文章主要介绍“Scala类型检查与模式匹配怎么使用”,在日...