Scala _占位符(此代码如何运行?)

时间:2011-07-30 01:02:06

标签: scala functional-programming placeholder

我正在学习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。该参数分配给queryfilesEnding然后使用与filesMatching函数一致的参数调用String => Boolean。最后,我可以看到file.getName最终取代了_占位符。

我没有得到的是Scala如何知道file.getName代替_。我无法在我的头脑中跟踪这段代码,而eclipse调试器在这种情况下帮助不大。有人可以告诉我这段代码中发生了什么吗?

2 个答案:

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

所以调用filesMatchingmatcher是函数x => x.endsWith(query),即一个函数接受一个参数x并在该参数上调用x.endsWith(query)。 / p>