Scala map以部分函数作为值

时间:2012-03-23 04:07:10

标签: scala

Twitter's Scala school collections section中,他们会将带有部分功能的地图显示为值:

// timesTwo() was defined earlier.
def timesTwo(i: Int): Int = i * 2
Map("timesTwo" -> timesTwo(_))

如果我尝试用Scala 2.9.1和sbt编译它,我会得到以下结果:

[error] ... missing parameter type for expanded function ((x$1) => "timesTwo".$minus$greater(timesTwo(x$1)))
[error]     Map("timesTwo" -> timesTwo(_))
[error]                                ^
[error] one error found

如果我添加参数类型:

Map("timesTwo" -> timesTwo(_: Int))

然后我得到以下编译器错误:

[error] ... type mismatch;
[error]  found   : Int => (java.lang.String, Int)
[error]  required: (?, ?)
[error]     Map("timesTwo" -> timesTwo(_: Int))
[error]                    ^
[error] one error found

我很难过。我错过了什么?

2 个答案:

答案 0 :(得分:5)

它认为你想这样做:

 Map((x: Int) => "timesTwo".->timesTwo(x))

如果你想要这个:

 Map("timesTwo" -> { (x: Int) => timesTwo(x) })

这样可行:

 Map( ("timesTwo", timesTwo(_)) )
 Map("timesTwo" -> { timesTwo(_) })

请注意,这不是常见错误,请参阅

(可能更多)

答案 1 :(得分:2)

您遗漏告诉scalac您希望方法 timesTwo提升 。这可以使用下划线完成,如下所示

scala> Map("timesTwo" -> timesTwo _)
res0: scala.collection.immutable.Map[java.lang.String,Int => Int] = Map(timesTwo -> <function1>)