switch with classifiers
Groovy's switch is the Java statement with a wider idea of a case: a case may be a constant, a class, a range, a regular expression or a closure, and the first one that matches wins.
Values and fall-through
values.groovy
def describe(int number) {
def text = ''
switch (number) {
case 1:
case 2:
text = 'one or two'
break
case 3:
text = 'three'
break
default:
text = 'many'
}
text
}
println describe(1)
println describe(2)
println describe(3)
println describe(9)
groovy values.groovy
one or two
one or two
three
many
Two case labels in a row share one block, which is Java's fall-through used on purpose. Without the break the next block runs too, and the value of the last assignment wins.
Classes, ranges and patterns
classify.groovy
def classify(value) {
def text = 'unknown'
switch (value) {
case 1..9:
text = 'a small number'
break
case Integer:
text = 'a whole number'
break
case ~/\d+/:
text = 'digits as text'
break
case String:
text = 'a string'
break
default:
text = 'something else'
}
text
}
println classify(5)
println classify(50)
println classify('42')
println classify('Groovy')
groovy classify.groovy
a small number
a whole number
digits as text
a string
The order matters: a range is tried before the Integer case, so 5 matches the range and 50 falls through to the class. A pattern case uses ==~, which asks whether the whole text matches, so '42' matches and 'Groovy' does not.
A closure as a case
A closure case is a predicate: the value is passed to it, and a true result selects the block. That is how a switch tests a property that no constant can name:
closure.groovy
def classify(List<Integer> numbers) {
def text = ''
switch (numbers) {
case { it.empty }:
text = 'empty'
break
case { it.every { int n -> n > 0 } }:
text = 'all positive'
break
default:
text = 'mixed'
}
text
}
println classify([])
println classify([1, 2, 3])
println classify([1, -2])
groovy closure.groovy
empty
all positive
mixed
A closure case is checked after the constant cases, so a switch that mixes both keeps the simple cases first and the predicates last.
Related
- if, else and the ternary: two branches and a value.
- Closures, it and parameters: the predicate of the last example.
Автор статьи: Arthur Isaev