I have seen this usage of Function.tupled example in another answer: Map(1 -> "one", 2 -> "two") map Function.tupled(_ -> _.length).
It works:
scala> Map(1 -> "one", 2 -> "two") map Function.tupled(_ -> _.length)
<console>:5: warning: method tupled in object Function is deprecated:
Use `f.tuple` instead
Map(1 -> "one", 2 -> "two") map Function.tupled(_ -> _.length)
^
res0: scala.collection.immutable.Map[Int,Int] = Map(1 -> 3, 2 -> 3)
It seems I can do without if I don’t want to use the placeholder syntax.
scala> Map(1 -> "one", 2 -> "two") map (x => x._1 -> x._2.length)
res1: scala.collection.immutable.Map[Int,Int] = Map(1 -> 3, 2 -> 3)
The direct use of the placeholder syntax does not work:
scala> Map(1 -> "one", 2 -> "two") map (_._1 -> _._2.length)
<console>:5: error: wrong number of parameters; expected = 1
Map(1 -> "one", 2 -> "two") map (_._1 -> _._2.length)
How does Function.tupled work? There seem to be a lot happening in Function.tupled(_ -> _.length). Also how would I use it to not get the deprecation warning?
UPDATE
The deprecation was removed today, in response to this problem.
Tupling a function is simply adapting
FunctionN[A1, A2, ..., AN, R]to aFunction1[(A1, A2, ..., AN), R]Function.tupleis deprecated in favour ofFunctionN#tupled. A (possibly unintended) consequence of this is that the type inferencer can’t infer the parameter types in:Any of these will work:
I suggest you read the answers to this recent question to get a deeper understanding of ‘_’ in function literals, and how type inferencing works:
In Scala, what is the difference between using the `_` and using a named identifier?
UPDATE
In answer to the comment, it does.
This requires Scala 2.8. Note that Map#map can result in another map, if the return type of the function is a
Tuple2, otherwise a List, as above.