在Twitter的Scala学校 集合部分,他们显示了一个具有部分功能的Map作为值:
// timesTwo() was defined earlier.
def timesTwo(i: Int): Int = i * 2
Map("timesTwo" -> timesTwo(_))
Run Code Online (Sandbox Code Playgroud)
如果我尝试用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
Run Code Online (Sandbox Code Playgroud)
如果我添加参数类型:
Map("timesTwo" -> timesTwo(_: Int))
Run Code Online (Sandbox Code Playgroud)
然后我得到以下编译器错误:
[error] ... type mismatch;
[error] found : Int => (java.lang.String, Int)
[error] required: (?, ?)
[error] Map("timesTwo" -> timesTwo(_: Int))
[error] ^
[error] one error found
Run Code Online (Sandbox Code Playgroud)
我很难过.我错过了什么?
它认为你想这样做:
Map((x: Int) => "timesTwo".->timesTwo(x))
Run Code Online (Sandbox Code Playgroud)
如果你想要这个:
Map("timesTwo" -> { (x: Int) => timesTwo(x) })
Run Code Online (Sandbox Code Playgroud)
这样可行:
Map( ("timesTwo", timesTwo(_)) )
Map("timesTwo" -> { timesTwo(_) })
Run Code Online (Sandbox Code Playgroud)
请注意,这不是通常的错误,请参阅
(可能更多)