The Java switch statement looks pale compared to Groovy's switch statement. In Groovy we can use different classifiers for a switch statement instead of only an int or int-derived type. Anything that implements the isCase() method can be used as a classifier. Groovy already added an isCase() method to Class (uses isInstance), Object (uses (equals), collections (uses contains) and regular expressions (uses matches). If we implement the isCase method in our own Groovy classes we can use it as a classifier as well. Finally we can a closure as a classifier. The closure will be evaluated to a boolean value.
def testSwitch(val) {
def result
switch (val) {
case ~/^Switch.*Groovy$/:
result = 'Pattern match'
break
case BigInteger:
result = 'Class isInstance'
break
case 60..90:
result = 'Range contains'
break
case [21, 'test', 9.12]:
result = 'List contains'
break
case 42.056:
result = 'Object equals'
break
case { it instanceof Integer && it < 50 }:
result = 'Closure boolean'
break
default:
result = 'Default'
break
}
result
}
assert 'Pattern match' == testSwitch("Switch to Groovy")
assert 'Class isInstance' == testSwitch(42G)
assert 'Range contains' == testSwitch(70)
assert 'List contains' == testSwitch('test')
assert 'Object equals' == testSwitch(42.056)
assert 'Closure boolean' == testSwitch(20)
assert 'Default' == testSwitch('default')
3 comments:
I agree with your comments, but you examples are a bit misleading, as the fall-through doesn't retest any of the case statements.
So if you changed the code to
def var = 42.056
switch (var) {
case Number:
assert true, 'Class isInstance'
// fallthrough
case 1..2:
assert true, 'Range contains'
// fallthrough
case [21, 'test', 9.12]:
assert true, 'List contains'
// fallthrough
case 1.42:
assert true, 'Object equals'
// fallthrough
case { it > 50 }:
assert true, 'Closure boolean'
break
default:
break
}
it would still be true :-)
You are right. In a real world sample we would add the breaks instead of falling through, because you showed what happens then.
Changed sample code so hopefully there is less confusion.
Post a Comment