问题描述
我正在尝试使用键定义一个Map文字: String
,value:(Any)=> String
。我尝试以下,但是得到一个语法错误:
I am trying to define a Map literal with key: String
, value: (Any)=>String
. I tried the following, but get a syntax error:
def foo(x: Int): String = /...
def bar(x: Boolean): String = /...
val m = Map[String, (Any) => String]("hello" -> foo, "goodbye" -> bar)
推荐答案
有趣的是,没有人实际上给出了将的类型。这是一个例子:
Funny that no one actually gave a type that would work. Here's one such:
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
的超类。
The reason why it works this way is because Function1
is contra-variant on the input, so (Nothing) => String
is a superclass of (Int) => String
. It is also co-variant on the output, so (Nothing) => Any
would be a superclass to any other Function1
.
当然可以不要这样用。没有清单,你甚至不能发现原始类型的 Function1
是什么。你可以尝试这样的东西:
Of course, you can't use it like that. Without manifests, you can't even uncover what the original type of Function1
is. You could try something like this, though:
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"
}
这篇关于在Scala中定义从字符串到函数的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!