Program structure in Groovy

This section explains the program structure in Groovy. You can refer to the official documentation of the Groovy language for more information.

On this page:

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 learn more about packages.

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 accessing classes of a package without package qualification. See here to learn more about imports.

For example, the MarkupBuilder class (for creating XML with Groovy) is inside the groovy.xml package. So, in order to use this class, you need to import it as shown:

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

Creating an object

In continuation to the above example, to create an XML you need to first create an object from the imported class as shown below:

// using the imported class to create an object
import groovy.xml.MarkupBuilder
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

In continuation to the above example, you can access a method using the "." dot syntax as shown in the below example:

import groovy.xml.MarkupBuilder
def xml = new MarkupBuilder()
//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 parenthesis () and the getter.

import groovy.xml.MarkupBuilder
def xml = new MarkupBuilder()
//Accessing a method of the class
xml.mkp

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 specifying its type, or using defWhen using def, the variable will be able to refer to objects of any type.

int x = 1
int y = 2
x + y == 3

x = 1
y = 2
x + y == 3