user1432980 user1432980 - 28 days ago 19
Groovy Question

list matching in groovy switch statement

Is there a way to achieve something like this in

groovy
?

def list1 = ['trs', 'file.xlsx', 'xxx']
def list2 = ['rls', 'file.xml', 'yyy']

def switchCheck(list) {
switch (list) {
case ['trs', /* matches pattern *.xlsx */ , /* any value */]:
println "trs message"
break
case ['rls', /* matches pattern *.xml */ , /* any value */]:
println "rls message"
break
default:
println "no match"
break
}
}

switchCheck(list1)
switchCheck(list2)


I want to check list data in the switch statement where some of its fields do not matter, while others should match a certain pattern (like ends with
*.xlsx
or
.xml
)

Answer Source

I just create a demonstration example because monkey patch is evil. You can modify isCase at runtime.

isCase is the method, when groovy calls in switch statement.(Different from Java)

Just call like this:

    ... // You don't need to modify switchCheck method.
    def list2 = ['rls', 'file.xml', 'yyy']
List.metaClass.isCase = { Object switchValue ->
    if (!switchValue in List && switchValue.size() == 3) {
        false
    } else {
        switchValue.first() == delegate.first() && (switchValue[1]) in ~(createRegexFromGlob(delegate[1]))
    }

}
switchCheck(list1)

The createRegexFromGlob is copied from here.