Dynamic Closures
We can determine whether a closure has been provided to us. Otherwise, we may decide to use a default implementation for, say, an algorithm in place of a specialized implementation the caller failed to provide. Here’s an example to figure out whether a closure is present:
UsingClosures/MissingClosure.groovy | |
| def doSomeThing(closure) { |
| if (closure) { |
| closure() |
| } else { |
| println "Using default implementation" |
| } |
| } |
| |
| doSomeThing() { println "Use specialized implementation" } |
| |
| doSomeThing() |
The code determines if a closure is provided and responds accordingly:
| Use specialized implementation |
| Using default implementation |
We also have quite a bit of flexibility in passing parameters. We can dynamically determine ...
Get Programming Groovy 2 now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.