Our new Appfire Documentation Space is now live!

Take a look here! If you have any questions please email support@appfire.com

Skip to end of metadata
Go to start of metadata

You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

To execute a block of code several number of times you would need Control structures. Groovy supports the usual 

  • Conditional statements: if-else, "nested" if then else if, switch, try-catch-finally
  • Looping statements: for, for-each, while loop, do while loop
  • Branching statements: break, continue, return
//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.

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.

// 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

for each - 



  • No labels