I would like to be able to define a function which accepts an argument (e.g. a File object), and returns something (e.g. a Boolean), and then pass that function (not the boolean!) to another function and have the accepting function call the sent function.
My background is in Java, and, although I know how to send a function which accepts no arguments and returns nothing in Scala, I can’t seem to find a good explanation on the internet for how to do this.
I could implement the program in Java, but I would really like to know how to do it in Scala.
First an example function (actually a method):
and a way to pass that function (actually a method) as an argument to another function (actually… you know…):
This method accepts a sequence of files and filters that sequence, picking only files passing a given predicate. In this case we return only existing files:
See how elegantly we pass
existsmethod as an argument? Or if you want to call the predicate manually:Side note: “…actually a method“
The
findFiles()method takespredicatefunction as an argument. HoweverfileExists()is a method – this works due to a mechanism called eta-expansion – transparently wrapping methods into functions.