DEV Community

Maxime Guilbert
Maxime Guilbert

Posted on • Updated on

A cool feature for your next Jenkinsfile - Closure

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()
  ...
}
Enter fullscreen mode Exit fullscreen mode

For more information, go check the official documentation which contains a lot of examples.


Links


I hope it will help you! 😀

Top comments (0)