4

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?

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Or Map("timesTwo" -> (timesTwo _))
or Map[String, Int => Int]("timesTwo" -> timesTwo)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.