Scala map with partial function as value

Twitter Scala School , 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 a parameter type:

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

Then I 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 at a dead end. What am I missing?

+4
source share
2 answers

He thinks you want to do this:

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

If you want to:

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

So this works:

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

Please note that this is not a common mistake, see

(and probably more)

+5
source

You were unable to tell scalac that you want to raise the timesTwo method to a function. This can be done using underscore as follows

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

Source: https://habr.com/ru/post/1403016/


All Articles