加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-16 19:05:43 所属栏目:安全 来源:网络整理
导读:我试图用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) 解决方法 有趣的是,
我试图用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"
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读