代码之家  ›  专栏  ›  技术社区  ›  huynhjl bhericher

Function.tuple和占位符语法

  •  11
  • huynhjl bhericher  · 技术社区  · 14 年前

    我在另一个例子中看到了Function.tuple的用法 answer : 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) . 另外,我如何使用它来不获得弃用警告?

    1 回复  |  直到 7 年前
        1
  •  15
  •   Community basarat    7 年前

    更新 反对意见是 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 ,否则为列表,如上所述。

    推荐文章