Scala中的闭包

sau*_*atz 2 closures scala

我正在尝试学习Scala,我无法理解这个例子.在Odersky等人的Scala编程9.1中.等,作者产生了这个代码

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))
}
Run Code Online (Sandbox Code Playgroud)

它们给出了一个场景,您正在编写一个由其他人编写的客户端代码使用的FileMatcher对象,而这段代码是几次重构的结果.

我理解查询是一个自由变量,但我不明白调用者应该如何使用它.由于Scala是,如果我理解正确,词汇范围,这是一个对象定义,客户端无法在词法封闭范围内定义查询,那么查询来自何处?

你能举个例子说明一个客户端应该如何调用filesEnding来查找以".txt"结尾的所有文件吗?

Dan*_*ral 6

试试吧.

scala> 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))
     | }
defined module FileMatcher

scala> FileMatcher filesEnding "xml"
res7: Array[java.io.File] = Array(./build.examples.xml, ./build.xml, ./build.detach.xml)

scala> FileMatcher filesContaining "example"
res8: Array[java.io.File] = Array(./build.examples.xml)
Run Code Online (Sandbox Code Playgroud)

如果您还有其他问题,请添加它们.