2013-06-19 107 views
1

为什么我能写这样的事情没有编译错误:斯卡拉关闭和下划线(_)符号

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

即我宣布x变量。

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

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

回答

3

您应该检查this answer about placeholder syntax

两个下划线的意思是两个连续的变量,所以使用println(_ + _)是一个占位符相当于(x, y) => println(x + y)

在第一个例子中,你只需要一个普通Tuple,这对于第一(._1)和第二(._2)元素访问。

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

2

每个下划线都是位置的。所以你的代码是desugared

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))