Groovy List Conversion
I'm having an issue in groovy trying to figure out how to convert a single item to a list. I have an incoming variable params.contacts
, which could be a single value (e.g. 14) or it could be an array of values (e.g. 14, 15). I want to 开发者_运维技巧always turn it into a list. Previously, I was simply saying params.contacts.toList()
, but this code fails when it's a single item. It would take a value of 14 and divide it into a list of [1, 4].
Is there a simple, elegant way of handling this problem?
One easy way, put it in a list and flatten it:
def asList(orig) {
return [orig].flatten()
}
assert [1, 2, 3, 4] == asList([1, 2, 3, 4])
assert ["foo"] == asList("foo")
assert [1] == asList(1)
One problem with this is that it'll completely flatten things, so it's not a good approach as it'll flatten lists within your list:
assert [[1, 2], [3, 4]] == asList([[1, 2], [3, 4]]) // fails!
Another way would be to use the type system to your advantage:
def asList(Collection orig) {
return orig
}
def asList(orig) {
return [orig]
}
assert [1, 2, 3, 4] == asList([1, 2, 3, 4])
assert ["foo"] == asList("foo")
assert [1] == asList(1)
assert [[1, 2], [3, 4]] == asList([[1, 2], [3, 4]]) // works!
Here, we let the type system do all the heavy lifting for us. If we've already got a collection, just return it. Otherwise, turn it into a list. Tricks like this from Java are still available to us in groovy, and we shouldn't completely throw them out when they're the right thing for the problem.
精彩评论