Note |
---|
You can Skip this tutorial if section if you are already know Groovy. You can refer to this page as a high-level reference to Groovy concepts and go ahead with familiar with the Groovy language and move on to the tutorials to start writing Groovy scripts in JMWE. |
This section of the document covers the syntax, keywords, operators, etc in the Groovy language.
...
location | top |
---|
Program structure
This section of the document gives an intorduction on the program structure in Groovy. You can refer to the official documentation of the Groovy language or any Java tutorial for complete information.
Packages
A package is a group of similar types of classes, interfaces and sub-packages. It is used to categorize the classes and interfaces so that they can be easily maintained. See here to know more about pacakges.
Definfing a package:
Code Block | ||||
---|---|---|---|---|
| ||||
// defining a package named com.yoursite
package com.yoursite
package javax.xml.parsers |
To refer to some class Foo
in the com.yoursite.com
package you will need to use the fully qualified name com.yoursite.com.Foo
, or else you can use an import
statement as shown below.
Imports
In order to refer to any class you need a qualified reference to its package. Groovy follows Java’s notion of allowing import
statement to resolve class references. The import allows to access classes of a package without package qualification. See here to know more about imports.
For example MarkupBuilder
is inside the package groovy.xml
so in order to use this class, you need to import
it as shown:
Code Block | ||||
---|---|---|---|---|
| ||||
// importing the class MarkupBuilder
import groovy.xml.MarkupBuilder |
Default imports:
Groovy automatically imports the packages groovy.lang.*, groovy.util.* , java.lang.* , java.util.* , java.net.* , and java.io.*
as well as the classes java.math.BigInteger
and BigDecimal
, since these are most commonly used.
Objects
In Groovy everything is an object that has methods and properties.
Code Block | ||||
---|---|---|---|---|
| ||||
// using the imported class to create an object
def xml = new MarkupBuilder() |
Methods
A method is a set of code which is referred to by name and can be invoked with parentheses ()
that may contain arguments. It can be invoked at any point in a program simply by utilizing its name. A method is where you put the operations on data (variables) in your Groovy code.
Accessing a method
You can access a method using the "." dot syntax as shown in the below example, where employee is the object that has accessors or methods to get Employee data
Code Block | ||||
---|---|---|---|---|
| ||||
//Accessing a method of the class
xml.getMkp() |
Direct access operator
You can use the direct access operator to call the property directly removing the paranthesis () and instead of using the getter.
Code Block | ||||
---|---|---|---|---|
| ||||
xml.mkp |
Script class
A script is always compiled into a class. The Groovy compiler will compile the class for you, with the body of the script copied into a run
method. For example:
Code Block | ||||
---|---|---|---|---|
| ||||
println 'Groovy world!' |
this will be compiled as if it was the following:
Code Block | ||||
---|---|---|---|---|
| ||||
import org.codehaus.groovy.runtime.InvokerHelper
class Main extends Script {
def run() {
println 'Groovy world!'
}
static void main(String[] args) {
InvokerHelper.runScript(Main, args)
}
} |
Variables
Variables are typically used to store information which your Groovy script needs to do its job on. See here for more information on Variables and their types.
Variable declaration
You can declare a variable either by specifiying its type or without specifying using def. The latter can be done using def
. This is because when using def
Groovy determines the methods to invoke at runtime, hence improving the flexibility. See official documentation for more information.
Code Block | ||||
---|---|---|---|---|
| ||||
int a,b
def a = 5
def b = 3
c = a + b |
Annotations
Annotation is a tag that represents the metadata i.e. attached with class, interface, methods or fields to indicate some additional information which can be used by java compiler and JVM. In Groovy, an annotation can be used to alter the semantics of the language. It is especially true of AST transformations which will generate code based on annotations.
Data types in Groovy
Groovy offers a wide variety of built-in data types. Following is a list of data types which are defined in Groovy
Booleans
true
and false
are the only two primitive boolean values.
Define a boolean object:
Code Block |
---|
boolean isActive = true
isActive = false |
Groovy has special rules to coerce non-boolean objects to a boolean value, referred as Truthy and Falsy. Groovy decides an expression as Truthy
when;
- If a boolean value is true
- Non-empty Collections and arrays are true
- True if the Matcher has at least one match
- Iterators and Enumerations with further elements are coerced to true
- Non-empty Maps are evaluated to true
- Non-empty Strings, GStrings and CharSequences are coerced to true
- Non-zero numbers are true
- Non-null object references are coerced to true
Any other value is considered Falsy. Eg: An empty string.
Collections
This section lists some of the collections in Groovy. See here for detailed information.
Lists
Groovy uses a comma-separated list of values, surrounded by square brackets, to denote lists. Groovy lists are plain JDK java.util.List
, as Groovy doesn’t define its own collection classes.
Initialising a list:
You can initialise a list delimiting the values by commas and surrounded by square brackets. You can also create lists containing values of heterogeneous types:
Code Block |
---|
def numbers = [1, 2, 3]
def hetero = [1, "a", true] |
Accessing a list:
- You can access the first element of the list on zero-based counting: hetero[0]
- You can access the last element of the list with a negative index: hetero[-1]
Set
A collection that contains no duplicate elements. Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. All these permit null values too.
HashSet:
A HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. HashSet stores the elements by using a mechanism called hashing. HashSet contains unique elements only.
LinkedHashSet:
LinkedHashSet class is a Hash table and Linked list implementation of the set interface. It inherits HashSet class and implements Set interface.
Initialising a Set/HashSet:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
def HashSet names = [] //Initialising a HashSet
set.add("Oliver")
set.add("Casper")
set.add("elvis")
set.add("Elvis")
set.add("John")
set.add("Carter")
set.add("Oliver")
names == [Oliver, Elvis, John, Casper, elvis, Carter] |
Maps
Groovy features maps. Maps associate keys to values, separating keys and values with colons, and each key/value pairs with commas, and the whole keys and values surrounded by square brackets.
Initialising a Map:
You need pass quoted strings if your key string isn’t a valid identifier Eg: "block-no". You must surround the variable or expression with parentheses, when you need to pass variable values as keys in your map definitions. Eg:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
def colors = [red: "#FF0000", green:"#00FF00", blue: "#0000FF"]
def doctor = [name: "Oliver","block-no":33,speciality:"Cardiology"]
place = [(address):"Oliver"] |
Accessing the elements of a Map:
- Check the content associated with the
red
key: colors["red"] - Add a pair to the Map: colors["pink"] = "#FF00FF" or colors.pink = "#FF00FF"
- Map contains a specific key: colors.blue == true
Arrays
Groovy reuses the list notation for arrays, but to make such literals arrays, you need to explicitly define the type of the array through coercion or type declaration. You can also create multi-dimensional arrays
Note |
---|
Note that Java’s array initializer notation is not supported by Groovy, as the curly braces can be misinterpreted with the notation of Groovy closures (discussed later). |
Initialising an Array :
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
String[] arrStr = ["Apple", "Banana", "Kiwi"] |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
def matrix3 = new Integer[3][3] //Array with bounds
def matrix = new String[][] //Array without bounds |
Accessing the elements of an array:
- Accessing the second element of the array: arrStr[1]
- Adding a new value to the array: arrStr[3] = "Mango"
- Accessing an element of the multi-dimensional array: matrix3[1][1]
Operators
Groovy supports all the typical operators, such as arithmetic operators, assignment operators, logical operators, relational operators and conditional operator. See below examples using some of the operators.
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
1 + 2 == 3
3 / 2 == 1.5
10 % 3 == 1
|
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
def a = 5
b = a += 3
b == 8
def c = 4
def d = c++
d == 5
def c = 5
c *= 3
c == 15
|
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
a > b
b - 3 == a
b + 3 != a
|
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
x and y
x || y
!x |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
!true == false
!'' == true |
...
title | Ternary operator and Elvis operator |
---|
The ternary operator is a shortcut expression that is equivalent to an if/else branch assigning some value to a variable.
Instead of:
Code Block | ||||
---|---|---|---|---|
| ||||
def text = "Test"
if (text!=null && text.length()>0) {
result = text
} else {
result = 'Empty'
} |
you can simplify it to:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
def text = "Test"
text ? text : 'Empty' |
Elvis operator is shortening of the ternary operator. You need not have to repeat the value you want to assign
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
def text = "Test"
text ?: 'Empty' |
There a few other notable operators that are specific only to the Groovy language; one of them is the Safe Navigation Operator.
Safe navigation operator
The Safe Navigation operator is used to avoid a NullPointerException. When you have a reference to an object you might need to verify that it is not null
before accessing methods or properties of the object. Using this operator, you can avoid this and directly return a null.
Normally you would have to:
Code Block | ||||
---|---|---|---|---|
| ||||
if(employee){
employee.getSalary()
} |
Instead, you can write it as:
Code Block | ||||
---|---|---|---|---|
| ||||
employee?.getSalary() |
Groovy Control structures
Groovy supports the usual if-else, "nested" if then else if, while loop, exception handling syntax.
Code Block | ||||
---|---|---|---|---|
| ||||
//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 | ||||
---|---|---|---|---|
| ||||
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 | ||||
---|---|---|---|---|
| ||||
// 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
...
tutorial details the following chapters:
Child pages (Children Display) |
---|