Versions Compared

Key

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

to To execute a block of code several number of timesonce or a multiple times based on a condition, you would need Control structures. Groovy supports the usual usual 

  • Conditional statements: if-else, "nested" if then else if, switch, try-catch-finally
  • Looping statements: for, for in, while loop

...

  • Branching statements: break, continue, return

See here for more information on the Control structures.

On this page:

Table of Contents

Conditional statements

Conditional statements execute a set of statements only if the condition is true

if

The if executes the statements if the condition is trueThe notable specialty of if in Groovy is, it plays well with the optional return statement. If your last expression of a method or closure (discussed later) is an if statement, then it is evaluated like an expression.

Code Block
languagegroovy
linenumberstrue
def x = 2

//Simple if
if(..x==2){
  (...)false
}

//Simple if else
if(..x == 2){
  (...)x = x + 2
}
else{
  (...)x = x - 2
}

//Nested if
if (...x) {
    x = x + ...1
} else if (...y) {
    y  ...= y + 1
} else {
    0
}

//Assign and test in nested expression
if ((x = 3)) {
 return true
}

//Optional return statement
def sysName = "Windows"
if (sysName...
}contains("Windows"))
 "We're on Windows."
 else
 "Oh, well we are on Mac"


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 xa = 1.235
def resultlog = ""

switch (a) x{
 )case {0 : log += "0" //|#1 fall
 case "fooDemo" : log += "Demo" //String
 case [2,3,5] : resultlog += "found5 foo"
 case 5..10 : log += "Range"  //Range
lets fall through

   case ~/d/ : log += "Regexmatch" //Regex
 case 1 "bar": log += "1" //|#1 through
 case 2 : resultlog += "bar2"; break
 default :  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.

...

log += 'default'
}
log == "5RangeRegexmatch12" //returns true

try-catch-finally

Exception handling is required in any programming language to handle the runtime errors so that normal flow of the application can be maintained. You can specify a complete try-catch-finally sequence of blocks, or just try-catch, or just try-finally to handle them. Braces are required around the block bodies whether or not they contain more than one statement.

Code Block
languagegroovy
linenumberstrue
def myMethod() {
 throw new IllegalArgumentException()
}
def log = []
try {
 myMethod()
} catch (Exception e) {
 log << e.toString()
} finally {
 log << "finally"
}
log.size() == 2 //returns true

Looping statements

Looping repeats the execution of a block of code multiple times. The loops available in Groovy are:

while loop

In a while loop the boolean test is evaluated, and if it's true, the body of the loop is then executed.

Code Block
languagegroovy
linenumberstrue
def list = [1, 2, 3]
while (list){
  list.remove(0)
}
list // returns []

Note: There is no do-while loop in Groovy

for/for-in loop

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

Code Block
languagegroovy
linenumberstrue
// Normal for loop
def x = 0
for (i = 0; i < 5; i++) {
    x += i;
  }
x == 10 //returns true

// iterate over a range
def x = 0
for ( i in 0..9 ) {
    x += i
}
x == 45 //returns true

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

//iterate over a list
def x = 0
def list = [10,12,13,14]; 
  for(j in list){
    x += j;
}
x == 49  //returns true
 
//iterate over a map
def x = 0
  def customers = [
    0 : "David",
    1 : "Elle",
    2 : "Peaches"
  ];

for(cust in customers){
    x += cust.key
  }
x ==  3 //returns true

//iterate over values of a Map
def x = ""
  def customers = [
    0 : "David",
    1 : "Elle",
    2 : "Peaches"
  ];

for(cust in customers){
    x += cust.value
  	x += ","
  }
x == "David,Elle,Peaches"  //returns true

// iterate over the characters in a string
def text = "abc"
def list = []
for (c in text) {
    list.add(c)
}
list == ["a", "b", "c"] //returns true

Branching statements

The branching statements are the loop controlling statements. Break and Continue can be used to control the workflow in codes that run in an endless loop.

break statementThe break statement is used to alter the flow of control inside loops and switch statements, explained above.for each

continue statement - The continue statement complements the break statement. Its use is restricted to while and for loops, explained above.

return statement - The last line of a method in Groovy is automatically the return statement. For this reason, an explicit return statement can be left out.