Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Groovy supports the usual if-else, "nested" if then else if, while loop, do while loop and exception handling syntax. 

Code Block
languagegroovy
linenumberstrue
//Simple if
if(..){
  (...)
}
//Simple if else
if(..){
  (...)
}
else{
  (...)
}
//Nested if
if (...) {
    ...
} else if (...) {
    ...
} else {
    ...
}

Switch statement - The switch statement executes one statement from multiple conditions. It is like if-else-if ladder statement. The switch statement in Groovy can handle any kind of switch value and different kinds of matching can be performed.

Code Block
languagegroovy
linenumberstrue
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
	default:
        result = "default"
}

In Groovy it is backward compatible with Java code, one difference though is that the Groovy switch statement can handle any kind of switch value and different kinds of matching can be performed.

for loop - for loop is used to iterate a part of the program several times. If the number of iteration is fixed, it is recommended to use for loop. In Groovy the for loop is much simpler and works with any kind of array, collection, Map, etc.

Code Block
languagegroovy
linenumberstrue
// iterate over a range
def x = 0
for ( i in 0..9 ) {
    x += i
}
x == 45

// iterate over an array
def array = (0..4).toArray()
x = 0
for ( i in array ) {
    x += i
}
x == 10

...