简体   繁体   中英

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:

// 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:

[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 . 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>)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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