我开始学习Scala,并且我遇到了Scala教程中的一个片段,我不太明白。希望有人能帮助我吗?了解Scala:将函数作为参数传递
这是来自程序清单9.1的Programming in Scala,2nd Edition。
object FileMatcher {
private def filesHere = (new java.io.File(".")).listFiles
}
private def filesMatching(matcher: String => Boolean) =
for (file <- filesHere; if matcher(file.getName)) yield file
def filesEnding(query: String) =
filesMatching(_.endsWith(query)) // ???
def filesContaining(query: String) =
filesMatching(_.contains(query)) // ???
def filesRegex(query: String) =
filesMatching(_.matches(query)) // ???
我和// ???
有点混淆。是否使用_
以某种方式创建了传递给filesMatching
的匿名函数?或者_
与此无关,而编译器看到filesMatching
需要一个函数,因此不会执行_.endsWith(query)
作为表达式,而是使该表达式成为函数?
上面没有任何包含'// ???'的行。也许你忘了添加这些? –
对不起,现在添加了'// ???'。 – C0deAttack
[Scala \ _占位符(此代码如何工作?)]的可能重复(http://stackoverflow.com/questions/6880407/scala-placeholders-how-does-this-code-function) –