'Groovy inject works locally but not on Jenkins?
I have the following script in a Jenkins () pipeline:
def imageTags = []
def semVerMatch = 'v0.0.0' =~ /(\d+(?:\.\d+)*)(-.*)?$/
if (semVerMatch.find()) {
List<String> versionNumber = semVerMatch[0][1].split("\\.") // e.g. 1.2.3
String versionSuffix = semVerMatch[0][2] ?: '' // e.g. -rc
imageTags += versionNumber[1,-1].inject([versionNumber[0]]) { acc, val ->
acc += "${acc[-1]}.${val}"
}.collect { "${it}${versionSuffix}" }
}
Running locally with the same Groovy version that seems to be used on that Jenkins (Groovy Shell (2.4.13, JVM: 11.0.12), oh my 😨), I get:
===> [0, 0.0, 0.0.0]
for imageTags, as expected.
On Jenkins, however, I get an error:
java.lang.NullPointerException: Cannot invoke method getAt() on null object
(Stacktrace useless, as per usual)
By println debugging (no idea how else to proceed), I have determined that acc == null in the second "iteration" of inject:
Why? And how do I fix it?
Solution 1:[1]
On a whim I tried adding a final expression to the closure that definitely returns the new value of acc:
imageTags += versionNumber[1,-1].inject([versionNumber[0]]) { acc, val ->
acc += "${acc[-1]}.${val}"
acc
}.collect { "${it}${versionSuffix}" }
For some reason, that works:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jeff Scott Brown |


