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

knp*_*wrs 6 functional-programming scala 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 */
}
Run Code Online (Sandbox Code Playgroud)

特别是我很困惑Scala获取_每个匹配器函数的值.我可以看到filesEnding用一个参数调用.txt.该论点被分配给query.filesEnding然后filesMatching使用与函数一致的参数调用String => Boolean.最后,我可以看到file.getName最终取代_占位符的内容.

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

ham*_*mar 17

_只是制作匿名函数的简写:

_.endsWith(query)
Run Code Online (Sandbox Code Playgroud)

与匿名函数相同

fileName => fileName.endsWith(query)
Run Code Online (Sandbox Code Playgroud)

然后将此函数作为参数提供matcherfilesMatching.在该功能内,您可以看到通话

matcher(file.getName)
Run Code Online (Sandbox Code Playgroud)

这将匿名函数file.getName作为_参数调用(我fileName在显式示例中调用).


sep*_*p2k 13

如果你写的_.someMethod(someArguments),这desugars到x => x.someMethod(someArguments),所以filesMatching(_.endsWith(query))desugars来filesMatching(x => x.endsWith(query)).

因此filesMatching,matcher作为函数调用x => x.endsWith(query),即一个接受一个参数x并调用x.endsWith(query)该参数的函数.

  • @KPthunder"节食" (2认同)