2012-01-18 5 views
2

스칼라를 배우려고하는데이 예제를 이해할 수 없습니다. Odersky et.가 작성한 Programming in Scala 9.1을 보면 알은., 저자는 그들은 당신이 다른 사람에 의해 쓰여진 클라이언트 코드가 사용할 FileMatcher 객체를 작성하는 시나리오를 줄이 코드스칼라 클로저

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)) 
} 

을 생산,이 코드는 리팩토링 부부의 결과입니다.

쿼리가 무료 변수라는 것을 알고 있지만 호출자가이를 사용하는 방법을 알지 못합니다. 스칼라가 올바르게 이해하고 어휘 적으로 범위가 지정되어 있고 이것이 객체 정의이기 때문에 클라이언트는 어휘 적으로 범위를 포함하는 쿼리를 정의 할 수 없으므로 쿼리는 어디서 오는가?

예를 들어, 클라이언트가 "파일"을 호출하여 ".txt"로 끝나는 모든 파일을 찾는 예를 들려 줄 수 있습니까?

+4

FileMatcher.filesEnding ("txt") – Apocalisp

+0

이렇게하면 클로저를 사용하여 직접 호출하지 않아도됩니다. 그러나 호출하는 메서드는 클로저를 사용합니다. _.endsWith (query) – thoredge

+1

쿼리는 완전히 표준 메서드 매개 변수입니다. – soc

답변

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) 

추가 질문이 있으면 추가하십시오.