August 14, 2009

Groovy Goodness: Use a Map as Interface Implementation

To implement an interface we can use a Groovy map and with the as keyword we can pass it on to a method. Here is a simple example where we define an implementation of the as a map. We pass the implementation on to the method to display all files with extensions .css and .png:

map = [ 
    // Implement FileFilter.accept(File) method.
    accept: { file -> file.path ==~ /.*\.(css|png)$/ } 
] as FileFilter
new File('c:/temp').listFiles(map).each { 
    println it.path 

If the interface we want to implement has more than one method we can only use a map for the implementation. But if the interface only contains one method (as in this case) we can also use a closure for the implementation. In the following example we implement the interface with a closure to filter all files with the extension .jpg:

filter = { it.path ==~ /.*\.jpg$/ }
new File('c:/temp').listFiles(filter as FileFilter).each { file ->
    println file.path