我正在尝试使用键:String,value:定义Map文本(Any)=>String.我尝试了以下,但得到语法错误:
def foo(x: Int): String = /...
def bar(x: Boolean): String = /...
val m = Map[String, (Any) => String]("hello" -> foo, "goodbye" -> bar)
Run Code Online (Sandbox Code Playgroud)
Dan*_*ral 10
搞笑的是居然没人给了一个类型,会工作.这是一个这样的:
def foo(x: Int): String = x.toString
def bar(x: Boolean): String = x.toString
val m = Map[String, (Nothing) => String]("hello" -> foo, "goodbye" -> bar)
Run Code Online (Sandbox Code Playgroud)
它以这种方式工作的原因是因为Function1输入是反变体的,所以它(Nothing) => String是一个超类(Int) => String.它也是输出的共同变体,因此(Nothing) => Any它将成为任何其他类型的超类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"
}
Run Code Online (Sandbox Code Playgroud)