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 56 Next »

You can Skip this tutorial if you already know Groovy. You can refer to this page as a high-level reference to Groovy concepts and go ahead with the tutorials to start writing Groovy scripts in JMWE.

This section of the document covers the syntax, keywords, operators, etc in the Groovy language.

Groovy Control structures

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

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

Optional omitting of syntax 

Groovy allows you to leave out some elements of syntax like package prefix, parentheses, and semicolon which brings the code to the bare minimum. 


References

  • No labels