Our new Appfire Documentation Space is now live!

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

Data types in Groovy

When you create a variable you reserve some space in memory to store the value associated with the variable. You may like to store information of various data types like string, character, wide character, integer, floating point, Boolean, etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Groovy offers built-in data types just as in Java. Following is a list of some useful data types:

See here for methods on how to manipulate the data types explained below.

On this page:

Simple data types

Groovy supports a limited set of datatypes at the language level; that is, it offers constructs for literal declarations and specialized operators. This section covers the simple datatypes like strings, regular expressions, and numbers.

Strings

Just like in Java, character data is mostly handled using the java.lang.String class. Groovy strings come in two flavors: plain strings and GStrings. Plain strings are instances of java.lang.String, and GStrings are instances of groovy.lang.GString. GStrings allow placeholder expressions (usually called string interpolation in many scripting languages) to be resolved and evaluated at runtime. See here for more information on Strings.

Plain Strings

Strings can be defined using single, double, triple single quotes or triple double quotes. All these are a series of characters surrounded by the respective quotes. Only double (double and triple double) quoted strings support interpolation. The triple quoted (triple single and triple double) strings are multi-line and you can span the content of the string across line boundaries without the need to split the string in several pieces, without contatenation or newline escape characters. Also, neither double quotes nor single quotes need to be escaped in triple double/single quoted strings.

String concatenation:

Groovy allows both + and - on Strings as shown in the example below.

Instantiating a String:

Strings
//Define strings with quotes
def a = "First String"
def b = 'Second String'

def multi-line = """First
Second
Third
lines"""

def multiline = '''Multiple
lines
with
triple single quotes'''

def multiline = '''Line
with
"double quotes"
in triple single quotes'''

//String concatenation
"Groovy" + " in JMWE" == "Groovy in JMWE"
"Groovy in JMWE" - " in" == "Groovy JMWE"

You can escape special characters in a String as explained here.

GStrings

Strings defined with double quotes (double quotes and triple double quotes) support interpolation. This allows you to substitute any Groovy expression into a String at the specified location. These are called GStrings. This is achieved using the ${} syntax. GStrings are implemented differently to capture the fixed and the dynamic parts (values) separately as shown in the example below.

GStrings
def name = "Groovy"
def greeting = "Welcome to ${name} language"
greeting == "Welcome to Groovy language"


greeting.strings[0] == "Welcome to "
greeting.strings[1] == " language"
greeting.values[0] == "Groovy"

Slashy Strings

The slashy form of a string literal allows strings with backslashes to be specified simply without having to escape all the backslashes. This is particularly useful with regular expressions discussed later on this page. 

Examples

Slashy Strings
def path = /C:\Windows\System32/
path == C:\Windows\System32 //returns true

def fooPattern = /.*foo.*/
fooPattern == ".*foo.*" //returns true

//Slashy strings are multiline
def multilineSlashy = /one
    two
    three/

multilineSlashy.contains('\n') //returns true

//Slashy strings can also be interpolated (ie. a GString)
def color = "blue"
def interpolatedSlashy = /a ${color} car/

interpolatedSlashy == "a blue car" //returns true

Note: An empty slashy string cannot be represented with a double forward slash (//), as it’s understood by the Groovy parser as a line comment.

Dollar slashy string

Dollar slashy strings are multiline GStrings delimited with an opening $/ and and a closing /$.

Dollar Slashy String
def name = "Groovy"
def name2 = "JMWE"

def dollarSlashy = $/
    Hello $name,
    we're ${name2}. /$

See here for more information on slashy strings.

Numbers

Numbers are objects in Groovy. Unlike in Java, they are first-class objects rather than primitive types. In Groovy, you can use numbers with numeric operators, and you can also call methods on number instances. See here for more information on numbers.

Numbers
def x = 1
def y = 2

x + y == 3
x.plus(y) == 3

Regular expressions

A regular expression is a pattern that is used to find substrings in a text. Groovy supports regular expressions natively using the ~”regex” expression. The text enclosed within the quotations represents the expression for comparison. See here for a table listing down all the regular expression metacharacter syntax. See here for more information on regular expressions.

Defining a regular expression

Regex
def regex = ~"Groovy"
def p = ~$/dollar/slashy $ string/$
def p = ~"${pattern}"

Groovy relies on Java's regex support and adds three operators for convenience:

  • The regex find operator =~
  • The regex match operator ==~
  • The regex pattern operator ~String

Groovy supports the following tasks for regular expressions:

  • Tell whether the pattern fully matches the whole string
  • Tell whether there is an occurrence of the pattern in the string
  • Count the occurrences
  • Do something with each occurrence
  • Replace all occurrences with some text
  • Split the string into multiple strings by cutting at each occurrence

Find operator

Returns a Matcher object if the string on the left-side contains the pattern on the right of the operator.

Find operator
def regex = ~/:[0-9]+/
def httpUrl1 = 'http://www.example.com:8080/'

httpUrl1 =~ regex //returns java.util.regex.Matcher[pattern=:[0-9]+ region=0,28 lastmatch=]

Match operator

Returns true if the string on the left-side matches (match must be strict) the pattern provided on the right of the operator

Match operator
def regex = ~/https?:\/\/.*/
def httpUrl = 'http://www.example.com/'

httpUrl ==~ regex //returns true

Pattern operator

The pattern operator (~) provides a simple way to create a java.util.regex.Pattern instance

Pattern operator
def p = ~"Groovy"
p instanceof java.util.regex.Pattern //returns true

Booleans

true and false are the only two primitive boolean values. See here for more information on this.

Defining a boolean object

Boolean
boolean isActive = true
isActive = false

Groovy has special rules to coerce non-boolean objects to a boolean value, referred as Truthy and Falsy. It decides whether to consider the expression as being true or false by asking the object for the result of its asBoolean() method. Groovy expression is Truthy when;

  • A boolean value is true
  • Non-empty Collections and Arrays are true
  • 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.

Arrays

An Array is an object that contains elements of similar data type. 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. Once an array has been created its size cannot be changed, you should use a List for dynamically-sized arrays. See here for more information on Arrays in Groovy.

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

Instantiating an Array:

Array[]
String[] arrStr = ["Apple", "Banana", "Kiwi"] 
arrStr[2] = "Mango" //Inserting element into an array


Array[][]
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]

Collections

Collections is a framework that provides an architecture to store and manipulate a group of objects. All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed on Collections. The Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc). This section lists some of the collections in Groovy. See here for detailed information on Collections.

List

The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index. It is a subinterface of Collection that contains methods to insert and delete elements on the index basis. Groovy lists are plain JDK java.util.List, as Groovy doesn’t define its own collection classes. You can create multi-dimensional lists too. See here for more information on Lists.

Instantiating a List:

You can initialize a list delimiting the values by commas and surrounded by square brackets. You can also create lists containing values of heterogeneous types:

List
def numbers = [1, 2, 3] //Elements of same data type
def hetero = [1, "a", true] //Elements of heterogenous data types

def multi = [[0, 1], [2, 3]]
multi[1][0] == 2 

List newValues = [] //Empty list

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]
  • Add an element to the list: numbers[3] = 5
  • Size of the list: numbers.size() == 4

Set

Set is a collection that contains no duplicate elements. Set has its implementation in various classes like HashSet, TreeSet, LinkedHashSet. All these permit null values too.

Instantiating a Set:

You can initialize a Set delimiting the values by commas and surrounded by square brackets. A Set can have values of heterogeneous types:

Set
Set 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.size() == 6

Set numbers = [3,4,6,"Special","@",5,1.2,3,4]
numbers as Set
numbers //returns [3, 4, 6, Special, @, 5, 1.2, 3, 4]

Set newValues = [] //Empty set

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. See here for more information on Maps.

Initialising a Map:

You need to pass quoted strings if your key string isn’t a valid identifier Eg: "block-no". You must surround a variable or expression with parentheses, when you need to it as a key in your map definition. Eg:

Map
def colors = [red: "#FF0000", green:"#00FF00", blue: "#0000FF"] 
def doctor = [name: "Oliver","block-no":33,speciality:"Cardiology"] //Map where the key isn't a valid identifier
place = [(address):"Oliver"] //Variable "address" as the key
def emptyMap = [:] //An empty map

Accessing the elements of a Map:

  • Check the value associated with the key, red: colors["red"]
  • Add a new pair to the Map: colors["pink"] = "#FF00FF" or colors.pink = "#FF00FF"
  • Check the Map contains a specific key: colors.blue == true

Ranges

A range is a shorthand for specifying a sequence of values. A range has a left bound and a right bound denoted by the first and last values in the sequence, and it can be inclusive or exclusive. An inclusive Range includes all the values from the first to the last, while an exclusive Range includes all values except the last. See here for more information on Ranges.

Instantiating a Range:

Range
def range = (0..10) //defining a range - Inclusive range
Range r = (0..<10)  //defining a range - Exclusive range

def today = new Date()
def yesterday = today-1
def days = yesterday..today

Accessing the elements of a Range:

  • Check the range contains a specific element: r.contains(10) == false
  • Size of the range: days.size() == 2