微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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"
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐