Set array to variable in groovy
Solution 1
This seems like a pretty contrived example, I'm not sure what you're really trying to do.
If url
is already a String
why not add it directly to SURL
? Putting it in "${}"
gives you a GString
instead.
It's not very Groovy to use a statically typed String array, just use a list.
def SURL = []
3.times {
SURL << url
}
This example uses the overloaded <<
operator to append to the list.
Solution 2
If you want to make it right, consider to define the array type explicitly. Instead of
def SURL = new String[3]
SURL[ 0 ] = "-- $a" // << here comes ArrayStoreException: org.codehaus.groovy.runtime.GStringImpl
do
String[] SURL = new String[3]
SURL[ 0 ] = "-- $a"
then it runs smoothly and groovy can properly outbox the GString
value to String
.
Solution 3
Ended up setting it as a string like this:
SURL[i]="${url}" as String
Still unsure why it's functioning this way. Maybe thinking it's an object?
Comments
-
Japster24 over 1 year
New to groovy and not a java lover. In my jenkinsfile, I'm having an issue with doing what I think would be simple.
SURL = new String[3] for (int i = 0; i < 3; i++) { url="value" SURL[i]="${url}" }
Seems like in this simple example that SURL[0] through SURL[2] would be set to "value". I'm getting the error:
java.lang.ArrayStoreException: org.codehaus.groovy.runtime.GStringImpl
Any help is appreciated. Thx!
-
Jayan almost 7 yearsJenkins pipeline is not really a plain groovy- The error you get is related to pipeline behavior
-
dsharew almost 7 yearsas @doelleri said it you are trying to assing GString to a String variable while in fact you dont need to use GString according to your code.
-