Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

An interface with a single method can be implemented with a closure like so:

Code Block
java
java
new// Thread(a readable puts {println "running"characters into a CharBuffer and returns the count of chars added
def readable = { it.put("12 34".reverse()); 5 } as Runnable
).start()
Readable

// the Scanner constructor can take a Readable
def s = new Scanner(readable)
assert s.nextInt() == 43

You can also use a closure to implement an interface with more than one method. The closure will be invoked for each method on the interface. Since you need a closure whose parameter list matches that of all of the methods you typically will want to use an array as the sole parameter. This can be used just as it is for any Groovy closure and will collect all of the arguments in an array. For example:

...