Search code examples
groovyjenkins-groovy

Idiomatic way to shallow clone or copy a map in Groovy


I want to shallow copy a map in my script so that I can update one of its keys. One way to do it is using spread operator. However, my script runs in Jenkins pipeline where spread operator is not allowed per company policy.

I try using clone() method, which works, but there is a warning "Access to 'clone' exceeds its access rights" in Intellij. It is partly because the map object is created from Jenkins readJSON method that may return map-like object and clone() method may not be implemented.

What is more idiomatic way to shallow copy a map other than spread operator?


Solution

  • You can use collectEntries(Closure.IDENTITY) - there is no no-arg version for maps, you have to pass in some version of an identity-fn