tags:

views:

77

answers:

2

I have a multiple select variable posting to controller. The way multiple select works is that it is passed as a single String if there was only one value selected and as a String[] if more than one values selected. I want to keep processing simple and treat the passed value(s) the same. So the best way I can up with is to convert it to List like so:

def selectedValues = params.selectedValues

List valuelist = new ArrayList()

if(selectedValues instanceof String) {
    valuelist.add(selectedValues)
} else {
    valuelist = selectedValues as List
}

It works but I am curious if there is a groovier way to do this, maybe with a one liner :).

Of course if I simply do:

List valuelist = selectedValues as List

It will not work for a single selected value as it will convert it from lets say 24 to [2,4]

Any ideas?

+5  A: 

You can use flatten to get that:

def toList(value) {
    [value].flatten().findAll { it != null }
}

assert( ["foo"] == toList("foo") )
assert( ["foo", "bar"] == toList(["foo", "bar"]) )
assert( [] == toList([]) )
assert( [] == toList(null) )

Or, if you don't want a separate method, you can do it as a one liner:

[params.selectedValues].flatten().findAll{ it != null }

I'd personally just write two methods and let the type system deal with it for me:

def toList(String value) {
    return [value]
}

def toList(value) {
    value ?: []
}

assert( ["foo"] == toList("foo") )
assert( ["foo", "bar"] == toList(["foo", "bar"]) )
assert( [] == toList([]) )
assert( [] == toList(null) )

It's more efficient and I think a little more obvious what's going on.

Ted Naleid
Thank you, I like the solution using flatten()
Micor
+2  A: 

try this:

def valueList = []
valueList = valueList + params?.selectedValues

Update: A couple other options depending on what you want the null case to be. As Ted pointed out, the above solution will return [null] when params?.selectedValues is null, which may not be what you want.

// if you want null to return []
def valueList = [] + (params?.selectedValues ?: [])

or

// if you want null to return null
def valueList = params?.selectedValues ? ([] + params?.selectedValues) : null
proflux
that doesn't work if selectedValues is null, but that's easily fixed with the if?then:else operator: def valueList = params?.selectedValues ? [] + params?.selectedValues : []
Ted Naleid
As written, my solution will return [null], the solution you propose will return [], and the solution Micor proposed will return null for selectedValues == null. You're right though, that may not be the desired behavior if a null value is a possibility.
proflux