Java 7 will have closures ( finally ), and I wonder how the existing code using single method classes/interfaces ( like Runnable, Comparator, etc ) will be used now.
Would that code be replaced? Will be a conversion of some sort? An extra method using the closure will be added?
Does anyone knows how is this going to work/what the plans are?
For instance, to use the FileFilter today we do:
....
File [] files = directory.listFiles( new FileFilter()
public boolean accept( File file ) {
return file.getName().endsWith(".java");
}
});
Does anyone knows how is this going to work on Java7?
Maybe overloading the method File.listFiles to receive a closure?
File [] files = directory.listFiles(#(File file){
return file.getName().endsWith(".java");
});
These classes/interfaces are called SAM (Single Abstract Method) types, and conversion of lambdas to SAM types is a central part of the project lambda proposal for JDK7. In fact, the most recent iteration of the proposal removes function types and only allows lambdas as instances of SAM types. With the latest version of the syntax (which is not final), your example could be written like:
File[] files = directory.listFiles(#(file){file.getName().endsWith(".java")});
With listFiles(FileFilter)
unchanged from what it is now.
You could also write
FileFilter javaFileFilter = {#(file){file.getName().endsWith(".java")};
You may also want to take a look at this State of the Lambda document which is the latest update to the proposal and explains things in more detail. Note also that the specifics are all subject to change, though it's pretty certain that a lambda expression/block will be usable as a SAM type like I've described.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With