【问题标题】:Scala closures and underscore (_) symbolScala 闭包和下划线 (_) 符号
【发布时间】:2013-06-15 20:33:45
【问题描述】:

为什么我可以写这样的东西而没有编译错误:

wordCount foreach(x => println("Word: " + x._1 + ", count: " + x._2)) // wordCount - is Map

即我声明了x 变量。

但在这种情况下我不能使用魔法_ 符号:

wordCount foreach(println("Word: " + _._1 + ", count: " + _._2)) // wordCount - is 

【问题讨论】:

    标签: scala closures


    【解决方案1】:

    每个下划线都是位置。所以你的代码被取消了

    wordCount foreach((x, y) => println("Word: " + x._1 + ", count: " + y._2))
    

    多亏了这个,List(...).reduce(_ + _) 才有可能。

    此外,由于 expansion is made relative to the closest paren 它实际上看起来像:

    wordCount foreach(println((x, y) => "Word: " + x._1 + ", count: " + y._2))
    

    【讨论】:

      【解决方案2】:

      你应该检查this answer about placeholder syntax

      两个下划线表示两个连续的变量,因此使用println(_ + _) 相当于(x, y) => println(x + y) 的占位符

      在第一个示例中,您只有一个常规 Tuple,它具有第一个 (._1) 和第二个 (._2) 元素的访问器。

      这意味着当您只想多次引用一个变量时,不能使用占位符语法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-01
        • 2011-08-28
        • 2010-09-12
        • 2017-09-19
        • 2019-12-01
        • 1970-01-01
        相关资源
        最近更新 更多