-
Notifications
You must be signed in to change notification settings - Fork 0
Flow Control
Philip Ford edited this page Aug 27, 2017
·
5 revisions
There isn't much to say here. Groovy has the usual structures from other C-based languages. But its switch statement is far more powerful than Java's. It is more like the switch statement JavaScript or in PHP.
The switch statement in Groovy is backwards compatible with Java code; so you can fall through cases sharing the same code for multiple matches. However, the Groovy switch statement can handle any kind of switch value and different kinds of matching can be performed.
def x = 1.23
def result = ""
switch ( x ) {
case "foo":
result = "found foo"
// lets fall through
case "bar":
result += "bar"
case [4, 5, 6, 'inList']:
result = "list"
break
case 12..30:
result = "range"
break
case Integer:
result = "integer"
break
case Number:
result = "number"
break
case ~/fo*/: // toString() representation of x matches the pattern?
result = "foo regex"
break
case { it < 0 }: // or { x < 0 }
result = "negative"
break
default:
result = "default"
}
assert result == "number"switch supports the following kinds of comparisons:
- Class case values match if the switch value is an instance of the class.
- Regular expression case values match if the
toString()representation of the switch value matches the regex. - Collection case values match if the switch value is contained in the collection. This also includes ranges (since they are Lists).
- Closure case values match if the calling the closure returns a result which is true according to the Groovy truth.1
- If none of the above are used then the case value matches if the case value equals the switch value.
Groovy supports the classic for-loop, and the newer Java for in loop for (String x : strings){...}.
Groovy's for loop also has a for...in variety which can work with arrays, collections, ranges, maps, etc.
// iterate over a range
def x = 0
for ( i in 0..9 ) {
x += i
}
assert x == 45
// iterate over a list
x = 0
for ( i in [0, 1, 2, 3, 4] ) {
x += i
}
assert x == 10
// iterate over an array
def array = (0..4).toArray()
x = 0
for ( i in array ) {
x += i
}
assert x == 10
// iterate over a map
def map = ['abc':1, 'def':2, 'xyz':3]
x = 0
for ( e in map ) {
x += e.value
}
assert x == 6
// iterate over values in a map
x = 0
for ( v in map.values() ) {
x += v
}
assert x == 6
// iterate over the characters in a string
def text = "abc"
def list = []
for (c in text) {
list.add(c)
}
assert list == ["a", "b", "c"]