简体   繁体   English

Scala map以部分函数作为值

[英]Scala map with partial function as value

In Twitter's Scala school collections section , they show a Map with a partial function as a value: Twitter的Scala学校 集合部分 ,他们显示了一个具有部分功能的Map作为值:

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

If I try to compile this with Scala 2.9.1 and sbt I get the following: 如果我尝试用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

If I add the parameter type: 如果我添加参数类型:

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

I then get the following compiler error: 然后我得到以下编译器错误:

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

I'm stumped. 我很难过。 What am I missing? 我错过了什么?

It thinks you want to do this: 它认为你想这样做:

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

When you want this: 如果你想要这个:

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

So this works: 这样可行:

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

Note this is not an usual error, see 请注意,这不是通常的错误,请参阅

(and probably more) (可能更多)

You are missing telling scalac that you want to lift the method timesTwo into a function . 你不想告诉scalac你想把方法 timesTwo 提升到一个函数中 This can be done with an underscore as follows 这可以通过下划线完成,如下所示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM