Note that there are some explanatory texts on larger screens.

plurals
  1. POQuestion on Scala Closure (From "Programming in Scala")
    primarykey
    data
    text
    <p>I don't understand why authors said that Code Listing 9.1 from "Programming in Scala" use closure. In chapter 9, they show how to refactor code into more less duplicated form, from this original code:</p> <pre><code>object FileMatcher { private def filesHere = (new java.io.File(".")).listFiles def filesEnding(query: String) = for (file &lt;- filesHere; if file.getName.endsWith(query)) yield file def filesContaining(query: String) = for (file &lt;- filesHere; if file.getName.contains(query)) yield file def filesRegex(query: String) = for (file &lt;- filesHere; if file.getName.matches(query)) yield file } </code></pre> <p>To the second version: </p> <pre><code>object FileMatcher { private def filesHere = (new java.io.File(".")).listFiles def filesMatching(query: String, matcher: (String, String) =&gt; Boolean) = { for (file &lt;- filesHere; if matcher(file.getName, query)) yield file } def filesEnding(query: String) = filesMatching(query, _.endsWith(_)) def filesContaining(query: String) = filesMatching(query, _.contains(_)) def filesRegex(query: String) = filesMatching(query, _.matches(_)) } </code></pre> <p>Which they said that there is no use of closure here. Now I understand until this point. However they introduced the use of <strong>closure</strong> to refactor even some more, shown in Listing 9.1:</p> <pre><code>object FileMatcher { private def filesHere = (new java.io.File(".")).listFiles private def filesMatching(matcher: String =&gt; Boolean) = for (file &lt;- 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)) } </code></pre> <p>Now they said that <strong>query</strong> is a free variable but I don't really understand why they said so? Since ""query"" seems to be passed from top method down to string matching function explicitly.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload