Definition
Definition from Apache Groovy
A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable.
The cool thing with closure is that we can use it as a parameter. With this, we are able to reuse a lot more of our code!
One case I met was to execute some scripts in a particular docker image. But the code to start the docker can take a lot of lines.
So, closures were really helpful! I was able to create a generic method to start a docker image and give a closure in parameter to execute inside the image.
Example
...
dockerLoader(param, ..., {
// some script to execute
})
...
def dockerLoader(param, ... closure: Closure) {
...
// Closure execution
closure()
...
}
For more information, go check the official documentation which contains a lot of examples.
Links
- Groovy documentation: https://groovy-lang.org/closures.html
- Baeldung Closure example: https://www.baeldung.com/groovy-closures
I hope it will help you! 😀
Top comments (0)