简体   繁体   中英

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!

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.

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 .

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM