Japster24
Japster24

Reputation: 1526

Set array to variable in groovy

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!

Upvotes: 1

Views: 12611

Answers (3)

injecteer
injecteer

Reputation: 20699

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.

Upvotes: 2

doelleri
doelleri

Reputation: 19682

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 GStringinstead.

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.

Upvotes: 3

Japster24
Japster24

Reputation: 1526

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?

Upvotes: 2

Related Questions