Function.tupled和占位符语法

时间:2010-03-01 06:51:43

标签: scala scala-2.8

我在另一个answerMap(1 -> "one", 2 -> "two") map Function.tupled(_ -> _.length)中看到了Function.tupled示例的这种用法。

有效:

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)

如果我不想使用占位符语法,我似乎无法做到。

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)

直接使用占位符语法不起作用:

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)

Function.tupled如何工作? Function.tupled(_ -> _.length)似乎发生了很多事情。另外我如何使用它来获取弃用警告?

1 个答案:

答案 0 :(得分:15)

<强>更新 鉴于此问题,今天的弃用率为removed


对函数进行元组化只是将FunctionN[A1, A2, ..., AN, R]调整为Function1[(A1, A2, ..., AN), R]

不推荐使用

Function.tuple,而是FunctionN#tupled。 (可能是非预期的)结果是类型推断器无法推断出参数类型:

scala> Map(1 -> "one", 2 -> "two") map (_ -> _.length).tupled                 
<console>:5: error: missing parameter type for expanded function ((x$1, x$2) => x$1.$minus$greater(x$2.length))
       Map(1 -> "one", 2 -> "two") map (_ -> _.length).tupled
                                        ^
<console>:5: error: missing parameter type for expanded function ((x$1: <error>, x$2) => x$1.$minus$greater(x$2.length))
       Map(1 -> "one", 2 -> "two") map (_ -> _.length).tupled

其中任何一个都可行:

scala> Map(1 -> "one", 2 -> "two") map { case (a, b)  => a -> b.length }
res8: scala.collection.immutable.Map[Int,Int] = Map(1 -> 3, 2 -> 3)

scala> Map(1 -> "one", 2 -> "two") map ((_: Int) -> (_: String).length).tupled           
res9: scala.collection.immutable.Map[Int,Int] = Map(1 -> 3, 2 -> 3)

scala> Map(1 -> "one", 2 -> "two") map ((p: (Int, String))  => p._1 -> p._2.length)
res12: scala.collection.immutable.Map[Int,Int] = Map(1 -> 3, 2 -> 3)

我建议你阅读这个最近问题的答案,以便更深入地理解函数文字中的'_',以及类型推理如何工作:

In Scala, what is the difference between using the `_` and using a named identifier?

<强>更新

在回答评论时,确实如此。

scala> val f = (x:Int, y:String) => x + ": " + y
f: (Int, String) => java.lang.String = <function2>

scala> f.tupled
res0: ((Int, String)) => java.lang.String = <function1>

scala> Map(1 -> "1") map f.tupled
res1: scala.collection.immutable.Iterable[java.lang.String] = List(1: 1)

这需要Scala 2.8。请注意,如果函数的返回类型为Tuple2,则Map #map可以生成另一个映射,否则为List,如上所述。

相关问题