red888 red888 - 3 years ago 300
Groovy Question

How do I default to a single element array?

Consider this:

alwaysBeArr = someFunc()
alwaysBeArr.each {
echo "${it.dump()}"

Sometimes someFunc() returns a list of strings sometimes just one string. If it only returns one string ".each{}" treats it like an arr of chars.

Is there a groovy way of making sure this is a single element array even if it only gets back a single string?

Answer Source

Consider the flatten() method. We create a list with the result (in either case), then flatten:

def someFunc = { ->
    (System.currentTimeMillis() % 2) ? 'mozart' : ['bach', 'beethoven', 'brahms'] 

def alwaysBeArr = [someFunc()].flatten()

alwaysBeArr.each { println it }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download