我正在学习Scala(来自大多数Java的背景)。我试图围绕以下代码:
object Main {
def main(args : Array[String]) {
for (file <- filesEnding(".txt"))
println(file.getName)
}
private val filesHere = (new java.io.File(".")).listFiles
def filesMatching(matcher: String => Boolean) =
for (file <- filesHere; if matcher(file.getName))
yield file
def filesEnding(query: String) = filesMatching(_.endsWith(query))
/* Other matcher functions */
}
特别是我很困惑,Scala在每个匹配器函数中获取_
的值。我可以看到filesEnding
的参数为.txt
。该参数分配给query
。 filesEnding
然后使用与filesMatching
函数一致的参数调用String => Boolean
。最后,我可以看到file.getName
最终取代了_
占位符。
我没有得到的是Scala如何知道file.getName
代替_
。我无法在我的头脑中跟踪这段代码,而eclipse调试器在这种情况下帮助不大。有人可以告诉我这段代码中发生了什么吗?
答案 0 :(得分:17)
_
只是制作匿名函数的简写:
_.endsWith(query)
与匿名函数
相同fileName => fileName.endsWith(query)
然后将此函数作为参数matcher
提供给filesMatching
。在该功能内,您可以看到呼叫
matcher(file.getName)
这将file.getName
作为_
参数调用匿名函数(在显式示例中我称之为fileName
)。
答案 1 :(得分:13)
如果你写_.someMethod(someArguments)
,这就是x => x.someMethod(someArguments)
,因此filesMatching(_.endsWith(query))
去了filesMatching(x => x.endsWith(query))
。
所以调用filesMatching
时matcher
是函数x => x.endsWith(query)
,即一个函数接受一个参数x
并在该参数上调用x.endsWith(query)
。 / p>