0

can any one helping me out to understand this code ...

object FileMatcher {
private def filesHere = (new java.io.File("C:/scalaTestcode")).listFiles
private def fileMatching(matcher : String => Boolean) =
{
   for(file <- filesHere; if matcher(file.getName)) yield file
}
def filesEnding(query:String) = 
  fileMatching {_.endsWith(query) }
def filesContaining(query:String) = 
  fileMatching {_.contains(query)}
def fileRegex(query:String)=
  fileMatching {_.matches(query)}
def main(args : Array[String])
{
  (filesEnding(".scala").toArray).foreach(println)
}
}

This code working properly and as expected. But what I am trying to understand how filesEnding method with "_" working. I mean when I am calling from main I am calling with Query as a param in filesEnding method , that passes the function to the fileMatching with "_". , that "_" got filled up with some string in fileMatching, but when I am trying to fileMatching with any other String it is giving compilation error , if "_" in this case means any String , that should works with any String or by "_" we are telling scala compiler that , this will filled up by somewhere else/at implementation.

Any detail explanation will be appreciated.... Thanks a lot ...

Biswajit
  • 323
  • 4
  • 15

4 Answers4

1

_.endsWith(query) is short for x => x.endsWith(query).

Jasper-M
  • 14,966
  • 2
  • 26
  • 37
1

_ can be used as a shorthand, meaning "use the value I'm operation on"

this may be useful: What are all the uses of an underscore in Scala?

In your case it could be replaced by the anonymous function: x => x.endsWith(query), but since it's not ambiguous, scala allows you to use that syntactic sugar

pedrorijo91
  • 7,635
  • 9
  • 44
  • 82
1

Let's start with fileMatching().

def fileMatching(matcher : String => Boolean) = ...

The argument matcher is a function that takes a String and returns a Boolean.

So that must be an accurate description of _.endsWith(query) and _.contains(query) and _.matches(query). All of these are functions that take a String, represented by the underscore, and return a Boolean.

Now how does the matcher argument get used?

... if matcher(file.getName) ...

So file.getName becomes the String that the _ represented, it is fed to the matcher() function, and the Boolean result is tested in the if clause.

jwvh
  • 50,871
  • 7
  • 38
  • 64
1

_ is usage of the placeholder Syntax. In essence, if each variable in the lambda signature is used only time, and each variable is used in the order given in the signature, you can replace each occurrence of the varaibles with _ and drop the signature because it is not ambiguous.

Since the code example you use is very similar to that used in the Book "Programming in Scala", you may want to go back a chapter to "8.5 Placeholder Syntax", where it is explained in detail.

EmilioMg
  • 376
  • 5
  • 14