WestCoastProjects
WestCoastProjects

Reputation: 63022

Assign an anonymous function to a scala method?

I may be way off here - but would appreciate insight on just how far ..

In the following getFiles method, we have an anonymous function being passed as an argument.

def getFiles(baseDir: String, filter: (File, String) => Boolean ) = {
 val ffilter = new FilenameFilter {
   // How to assign to the anonymous function argument 'filter' ?
   override def accept(dir: File, name: String): Boolean = filter  
 }
 ..

So that override is quite incorrect: that syntax tries to evaluate the filter() function which results in a Boolean.

Naturally we could simply evaluate the anonymous function as follows:

 override def accept(dir: File, name: String): Boolean = filter(dir, name)  

But that approach does not actually replace the method .

So: how to assign the accept method to the filter anonymous function?

Update the error message is

Error:(56, 64) type mismatch;
 found   : (java.io.File, String) => Boolean
 required: Boolean
       override def accept(dir: File, name: String): Boolean = filter // { filter(dir, name) }

Another update Thinking more on this - and am going to take a swag : Dynamic languages like python and ruby can handle assignment of class methods to arbitrary functions. But scala requires compilation and thus the methods are actually static. A definitive answer on this hunch would be appreciated.

Upvotes: 2

Views: 592

Answers (2)

Sean Vieira
Sean Vieira

Reputation: 159865

There is no way easy or type-safe way (that I know of) to assign a function to a method as they are different types. In Python or JavaScript you could do something like this:

var fnf = new FilenameFilter();
fnf.accepts = filter;

But in Scala you have to do the delegation:

val fnf = new FilenameFilter {
   override def accept(dir: File, name: String): Boolean = filter(dir, name) 
 }

Upvotes: 1

Attila Repasi
Attila Repasi

Reputation: 1830

I think you are actually misunderstanding the meaning of the override keyword. It is for redefining methods defined in the superclass of a class, not redefining a method in an instance of a class.

If you want to redefine the accept method in the instances of FilenameFilter, you will need to add the filter method to the constructor of the class, like:

class FilenameFilter(val filter: (File, String) => Boolean) {
  def accept(dir: File, name: String): Boolean = filter(dir, name)
}

Upvotes: 0

Related Questions