| |
| 1 Logical branching |
| |
| Groovy supports the usual if - else syntax from Java |
| |
| {code:groovy} |
| x = false |
| y = false |
| |
| if ( !x ) { |
| x = true |
| } |
| |
| assert x == true |
| |
| if ( x ) { |
| x = false |
| } else { |
| y = true |
| } |
| |
| assert x == y |
| {code} |
| |
| Groovy also supports the ternary operator |
| |
| {code:groovy} |
| y = 5 |
| x = (y > 1) ? "worked" : "failed" |
| assert x == "worked" |
| {code} |
| |
| |
| 1.1 switch statement |
| |
| The switch statement in Groovy is backwards compatible with Java code; so you can fall through cases sharing the same code for multiple matches. |
| |
| One difference though is that the Groovy switch statement can handle any kind of switch value and different kinds of matching can be performed. |
| |
| {code:groovy} |
| x = 1.23 |
| 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 |
| |
| default: |
| result = "default" |
| } |
| |
| assert result == "number" |
| {code} |
| |
| Switch supports the following kinds of comparisons |
| |
| * Class case values matches if the switchValue is an instanceof the class |
| * Regular expression case value matches if the string of the switchValue matches the regex |
| * Collection case value matches if the switchValue is contained in the collection. This also includes ranges too (since they are Lists) |
| * if none of the above are used then the case value matches if the case value equals the switch value |
| |
| 1.1 How switch works |
| |
| The case statement performs a ~~match~~ on the case value using the ~~isCase(switchValue)~~ method, |
| which defaults to call ~~equals(switchValue)~~ but has been overloaded for various types like Class or regex etc. |
| |
| So you could create your own kind of matcher class and overload the isCase(switchValue) method to provide your own kind of matching. |