Groovy Syntax
Groovy Syntax
Table of contents
1. Comments
2. Keywords
3. Identifiers
4. Strings
4.9. Characters
5. Numbers
Binary literal
Octal literal
Hexadecimal literal
6. Booleans
7. Lists
8. Arrays
9. Maps
Syntax
This chapter covers the syntax of the Groovy programming language. The grammar of the
language derives from the Java grammar, but enhances it with specific constructs for Groovy,
and allows certain simplifications.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 2/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
1. Comments
1.1. Single-line comment
Single-line comments start with // and can be found at any position in the line. The
characters following // , until the end of the line, are considered part of the comment.
methods definitions
Although the compiler will not complain about Groovydoc comments not being associated
with the above language elements, you should prepend those constructs with the comment
right before it.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 3/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
/**
* A Class description
*/
class Person {
/** the name of the person */
String name
/**
* Creates a greeting method for a certain person.
*
* @param otherPerson the person to greet
* @return a greeting message
*/
String greet(String otherPerson) {
"Hello ${otherPerson}"
}
}
Groovydoc follows the same conventions as Java’s own Javadoc. So you’ll be able to use the
same tags as with Javadoc.
In addition, Groovy supports Runtime Groovydoc since 3.0.0, i.e. Groovydoc can be retained at
runtime.
The Runtime Groovydoc starts with /**@ and ends with */ , for example:
/**@
* Some class groovydoc for Foo
*/
class Foo {
/**@
* Some method groovydoc for bar
*/
void bar() {
}
}
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 4/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
#!/usr/bin/env groovy
println "Hello from the shebang line"
The # character must be the first character of the file. Any indentation
would yield a compilation error.
2. Keywords
Groovy has the following reserved keywords:
Of these, const , goto , strictfp , and threadsafe are not currently in use.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 5/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
The reserved keywords can’t in general be used for variable, field and method names.
A trick allows methods to be defined having the same name as a keyword by surrounding the
name in quotes as shown in the following example:
Using such names might be confusing and is often best to avoid. The trick is primarily intended
to enable certain Java integration scenarios and certain DSL (https://docs.groovy-
lang.org/latest/html/documentation/core-domain-specific-languages.html) scenarios where
having "verbs" and "nouns" with the same name as keywords may be desirable.
as in permitsrecord
These words are only keywords in certain contexts and can be more freely used in some
places, in particular for variables, fields and method names.
This extra lenience allows using method or variable names that were not keywords in earlier
versions of Groovy or are not keywords in Java. Examples are shown here:
Groovy programmers familiar with these contextual keywords may still wish to avoid using
those names unless there is a good reason to use such a name.
The restrictions on reserved keywords also apply for the primitive types, the boolean literals
and the null literal (all of which are discussed later):
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 6/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
While not recommended, the same trick as for reserved keywords can be used:
Using such words as method names is potentially confusing and is often best to avoid,
however, it might be useful for certain kinds of DSLs (https://docs.groovy-
lang.org/latest/html/documentation/core-domain-specific-languages.html).
3. Identifiers
3.1. Normal identifiers
Identifiers start with a letter, a dollar or an underscore. They cannot start with a number.
'\u00C0' to '\u00D6'
'\u00D8' to '\u00F6'
'\u00F8' to '\u00FF'
'\u0100' to '\uFFFE'
def name
def item3
def with_underscore
def $dollarStart
def 3tier
def a+b
def a#b
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 7/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
foo.as
foo.assert
foo.break
foo.case
foo.catch
As we shall see in the following section on strings, Groovy provides different string literals. All
kind of strings are actually allowed after the dot:
map.'single quote'
map."double quote"
map.'''triple single quote'''
map."""triple double quote"""
map./slashy string/
map.$/dollar slashy string/$
There’s a difference between plain character strings and Groovy’s GStrings (interpolated
strings), as in that the latter case, the interpolated values are inserted in the final string for
evaluating the whole identifier:
4. Strings
Text literals are represented in the form of chain of characters called strings. Groovy lets you
instantiate java.lang.String objects, as well as GStrings ( groovy.lang.GString ) which are
also called interpolated strings in other programming languages.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 8/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
Triple-single-quoted strings may span multiple lines. The content of the string can cross line
boundaries without the need to split the string in several pieces and without concatenation or
newline escape characters:
If your code is indented, for example in the body of the method of a class, your string will
contain the whitespace of the indentation. The Groovy Development Kit contains methods for
stripping out the indentation with the String#stripIndent() method, and with the
String#stripMargin() method that takes a delimiter character to identify the text to remove
from the beginning of a string.
You will notice that the resulting string contains a newline character as first character. It is
possible to strip that character by escaping the newline with a backslash:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 9/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
assert !strippedFirstNewline.startsWith('\n')
And you can escape the escape character itself with a double backslash:
\b backspace
\f formfeed
\n newline
\r carriage return
\s single space
\t tabulation
\\ backslash
We’ll see some more escaping details when it comes to other types of strings discussed later.
For characters that are not present on your keyboard, you can use unicode escape sequences:
a backslash, followed by 'u', then 4 hexadecimal digits.
Any Groovy expression is valid, as we can see in this example with an arithmetic expression:
Not only are expressions allowed in between the ${} placeholder, but so
are statements. However, a statement’s value is just null . So if several
statements are inserted in that placeholder, the last one should somehow
return a meaningful value to be inserted. For instance, "The sum of 1 and 2 is
equal to ${def a = 1; def b = 2; a + b}" is supported and works as expected
but a good practice is usually to stick to simple expressions inside GString
placeholders.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 11/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
In addition to ${} placeholders, we can also use a lone $ sign prefixing a dotted expression:
But only dotted expressions of the form a.b , a.b.c , etc, are valid. Expressions containing
parentheses like method calls, curly braces for closures, dots which aren’t part of a property
expression or arithmetic operators would be invalid. Given the following variable definition of
a number:
shouldFail(MissingPropertyException) {
println "$number.toString()"
}
Similarly, if the expression is ambiguous, you need to keep the curly braces:
If you need to escape the $ or ${} placeholders in a GString so they appear as is without
interpolation, you just need to use a \ backslash character to escape the dollar sign:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 12/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
In appearance, it looks like a more verbose way of defining expressions to be interpolated, but
closures have an interesting advantage over mere expressions: lazy evaluation.
def number = 1 1
def eagerGString = "value == ${number}"
def lazyGString = "value == ${ -> number }"
number = 2 4
assert eagerGString == "value == 1" 5
assert lazyGString == "value == 2" 6
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 13/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
GString and Strings having different hashCode values, using GString as Map keys should be
avoided, especially if we try to retrieve an associated value with a String instead of a GString.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 14/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
Yours sincerly,
Dave
"""
assert template.toString().contains('Groovy')
assert multilineSlashy.contains('\n')
Slashy strings can be thought of as just another way to define a GString but with different
escaping rules. They hence support interpolation:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 15/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
An empty slashy string cannot be represented with a double forward slash, as it’s understood
by the Groovy parser as a line comment. That’s why the following assert would actually not
compile as it would look like a non-terminated statement:
assert '' == //
As slashy strings were mostly designed to make regexp easier so a few things that are errors in
GStrings like $() or $5 will work with slashy strings.
Remember that escaping backslashes is not required. An alternative way of thinking of this is
that in fact escaping is not supported. The slashy string /\t/ won’t contain a tab but instead a
backslash followed by the character 't'. Escaping is only allowed for the slash character, i.e.
/\/folder/ will be a slashy string containing '/folder' . A consequence of slash escaping is
that a slashy string can’t end with a backslash. Otherwise that will escape the slashy string
terminator. You can instead use a special trick, /ends with slash ${'\'}/ . But best just
avoid using a slashy string in such a case.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 16/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
def dollarSlashy = $/
Hello $name,
today we're ${date}.
$ dollar sign
$$ escaped dollar sign
\ backslash
/ forward slash
$/ escaped forward slash
$$$/ escaped opening dollar slashy
$/$$ escaped closing dollar slashy
/$
assert [
'Guillaume',
'April, 1st',
'$ dollar sign',
'$ escaped dollar sign',
'\\ backslash',
'/ forward slash',
'/ escaped forward slash',
'$/ escaped opening dollar slashy',
'/$ escaped closing dollar slashy'
].every { dollarSlashy.contains(it) }
It was created to overcome some of the limitations of the slashy string escaping rules. Use it
when its escaping rules suit your string contents (typically if it has some slashes you don’t want
to escape).
Single-quoted '…' \
Triple-single-
'''…''' \
quoted
Double-quoted "…" \
Triple-double-
"""…""" \
quoted
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 17/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
Slashy /…/ \
4.9. Characters
Unlike Java, Groovy doesn’t have an explicit character literal. However, you can be explicit
about making a Groovy string an actual character, by three different means:
char c1 = 'A' 1
assert c1 instanceof Character
def c3 = (char)'C' 3
assert c3 instanceof Character
by being explicit when declaring a variable holding the character by specifying the char
1
type
2 by using type coercion with the as operator
3 by using a cast to char operation
The first option 1 is interesting when the character is held in a variable,
while the other two ( 2 and 3 ) are more interesting when a char value
must be passed as argument of a method call.
5. Numbers
Groovy supports different kinds of integral literals and decimal literals, backed by the usual
Number types of Java.
byte
char
short
int
long
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 18/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
java.math.BigInteger
You can create integral numbers of those types with the following declarations:
// primitive types
byte b = 1
char c = 2
short s = 3
int i = 4
long l = 5
// infinite precision
BigInteger bi = 6
If you use optional typing by using the def keyword, the type of the integral number will vary:
it’ll adapt to the capacity of the type that can hold that number.
def a = 1
assert a instanceof Integer
// Integer.MAX_VALUE
def b = 2147483647
assert b instanceof Integer
// Integer.MAX_VALUE + 1
def c = 2147483648
assert c instanceof Long
// Long.MAX_VALUE
def d = 9223372036854775807
assert d instanceof Long
// Long.MAX_VALUE + 1
def e = 9223372036854775808
assert e instanceof BigInteger
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 19/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
def na = -1
assert na instanceof Integer
// Integer.MIN_VALUE
def nb = -2147483648
assert nb instanceof Integer
// Integer.MIN_VALUE - 1
def nc = -2147483649
assert nc instanceof Long
// Long.MIN_VALUE
def nd = -9223372036854775808
assert nd instanceof Long
// Long.MIN_VALUE - 1
def ne = -9223372036854775809
assert ne instanceof BigInteger
Binary literal
Binary numbers start with a 0b prefix:
Octal literal
Octal numbers are specified in the typical format of 0 followed by octal digits.
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 20/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
Hexadecimal literal
Hexadecimal numbers are specified in the typical format of 0x followed by hex digits.
float
double
java.math.BigDecimal
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 21/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
You can create decimal numbers of those types with the following declarations:
// primitive types
float f = 1.234
double d = 2.345
// infinite precision
BigDecimal bd = 3.456
Decimals can use exponents, with the e or E exponent letter, followed by an optional sign,
and an integral number representing the exponent:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 22/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
Type Suffix
BigInteger G or g
Long L or l
Integer I or i
BigDecimal G or g
Double D or d
Float F or f
Examples:
binary operations between byte , char , short and int result in int
binary operations involving long with byte , char , short and int result in long
binary operations involving BigInteger and any other integral type result in
BigInteger
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 23/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
binary operations involving BigDecimal with byte , char , short , int and
BigInteger result in BigDecimal
byte int int int int long BigInteger double double BigDecimal
BigDecimal BigDecimal
BigDecimal division is performed with the divide() method if the division is exact (i.e.
yielding a result that can be represented within the bounds of the same precision and scale),
or using a MathContext with a precision
(http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#precision()) of the
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 24/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
maximum of the two operands' precision plus an extra precision of 10, and a scale
(http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#scale()) of the
maximum of 10 and the maximum of the operands' scale.
For integer division like in Java, you should use the intdiv() method, as
Groovy doesn’t provide a dedicated integer division operator symbol.
The following rules are used by Groovy’s power operation to determine the resulting type:
if the base is an Integer , then return an Integer if the result value fits in
it, otherwise a BigInteger
if the base is a Long , then return a Long if the result value fits in it,
otherwise a BigInteger
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 25/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
// base and exponent are ints and the result can be represented by an In
teger
assert 2 ** 3 instanceof Integer // 8
assert 10 ** 9 instanceof Integer // 1_000_000_000
6. Booleans
Boolean is a special data type that is used to represent truth values: true and false . Use
this data type for simple flags that track true/false conditions (https://docs.groovy-
lang.org/latest/html/documentation/core-operators.html#_conditional_operators).
Boolean values can be stored in variables, assigned into fields, just like any other data type:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 26/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
true and false are the only two primitive boolean values. But more complex boolean
expressions can be represented using logical operators (https://docs.groovy-
lang.org/latest/html/documentation/core-operators.html#_logical_operators).
7. 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. The concrete list implementation used when defining list literals are
java.util.ArrayList by default, unless you decide to specify otherwise, as we shall see later
on.
We define a list numbers delimited by commas and surrounded by square brackets, and
1
we assign that list into a variable
2 The list is an instance of Java’s java.util.List interface
The size of the list can be queried with the size() method, and shows our list contains
3
3 elements
In the above example, we used a homogeneous list, but you can also create lists containing
values of heterogeneous types:
We mentioned that by default, list literals are actually instances of java.util.ArrayList , but
it is possible to use a different backing type for our lists, thanks to using type coercion with the
as operator, or with explicit type declaration for your variables:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 27/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
You can access elements of the list with the [] subscript operator (both for reading and
setting values) with positive indices or negative indices to access elements from the end of the
list, as well as with ranges, and use the << leftShift operator to append elements to a list:
letters[2] = 'C' 3
assert letters[2] == 'C'
As lists can be heterogeneous in nature, lists can also contain other lists to create
multidimensional lists:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 28/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
8. 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.
Integer[][] matrix2 2
matrix2 = [[1, 2], [3, 4]]
assert matrix2 instanceof Integer[][]
1 You can define the bounds of a new array
2 Or declare an array without specifying its bounds
names[2] = 'Blackdrag' 2
assert names[2] == 'Blackdrag'
1 Retrieve the first element of the array
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 29/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
2 Set the value of the third element of the array to a new value
Examples:
9. Maps
Sometimes called dictionaries or associative arrays in other languages, 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.
colors['pink'] = '#FF00FF' 4
colors.yellow = '#FFFF00' 5
We define a map of string color names, associated with their hexadecimal-coded html
1
colors
2 We use the subscript notation to check the content associated with the red key
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 30/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
We can also use the property notation to assert the color green’s hexadecimal
3
representation
4 Similarly, we can use the subscript notation to add a new key/value pair
5 Or the property notation, to add the yellow color
When using names for the keys, we actually define string keys in the map.
Groovy creates maps that are actually instances of
java.util.LinkedHashMap .
In the examples above, we used string keys, but you can also use values of other types as keys:
assert !person.containsKey('name') 2
assert person.containsKey('key') 3
The key associated with the 'Guillaume' name will actually be the "key" string, not
1
the value associated with the key variable
2 The map doesn’t contain the 'name' key
3 Instead, the map contains a 'key' key
You can also pass quoted strings as well as keys: ["name": "Guillaume"]. This
is mandatory if your key string isn’t a valid identifier, for example if you
wanted to create a string key containing a dash like in: ["street-name": "Main
street"].
When you need to pass variable values as keys in your map definitions, you must surround the
variable or expression with parentheses:
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 31/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
assert person.containsKey('name') 2
assert !person.containsKey('key') 3
This time, we surround the key variable with parentheses, to instruct the parser we are
1
passing a variable rather than defining a string key
2 The map does contain the name key
3 But the map doesn’t contain the key key as before
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 32/33
4/6/24, 6:50 PM The Apache Groovy programming language - Syntax
https://groovy-lang.org/syntax.html#_triple_single_quoted_string 33/33