Scala _ Placeholders (how does this code work?)

I am learning Scala (coming from background mostly Java). I am trying to wrap my head around the following code:

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 */ } 

In particular, I am confused when Scala gets the value for _ in each of the conjugate functions. I see that filesEnding is filesEnding called with the .txt argument. This argument is assigned to query . filesEnding then calls filesMatching with an argument consistent with String => Boolean . Finally, I see that file.getName is what ultimately replaces the _ placeholder.

I do not understand how Scala knows file.getName instead of _ . I'm having trouble tracking this code in my head, and the eclipse debugger doesn't help much in this situation. Can someone get me through what is going on in this code?

+6
source share
2 answers

_ is just a shorthand for an anonymous function:

 _.endsWith(query) 

matches anonymous function

 fileName => fileName.endsWith(query) 

This function is matcher as the filesMatching argument to filesMatching . Inside this function you can see the call

 matcher(file.getName) 

This calls an anonymous function with file.getName as the _ argument (which I named fileName in an explicit example).

+17
source

If you write _.someMethod(someArguments) , these are desugars on x => x.someMethod(someArguments) , therefore filesMatching(_.endsWith(query)) desugars on filesMatching(x => x.endsWith(query)) .

So, filesMatching is called with matcher as a function x => x.endsWith(query) , that is, a function that takes one argument x and calls x.endsWith(query) on that argument.

+13
source

Source: https://habr.com/ru/post/893919/


All Articles