我在另一个答案中看到了 Function.tupled 示例的这种用法:Map(1 -> "one", 2 -> "two") map Function.tupled(_ -> _.length)
。
有用:
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)
。另外,我将如何使用它来不收到弃用警告?