Blog

Told you, we love sharing!

Multiple Variable Assignment in Groovy

  • Application Security
  • Automation Testing
  • Cloud Managed Services
  • Connected TV
  • Data & Analytics
  • Digital Analytics
  • Digital Engineering
  • Digital Marketing
  • Digital Transformation
  • DM – Analytics
  • Experience Design
  • Front End Development
  • Industry Buzz
  • Manual Testing
  • Marketing Automation
  • Mobile Automation Testing
  • Product Engineering
  • Software development
  • User Experience
  • Video Solutions
  • Web Content Management

In one of my project, I was in need to return multiple variables from a method. I searched and found very good Groovy way for ‘Multiple Assignment’, This allows us to assign multiple variables at once.

[groovy]def (str1,str2,str3) = [‘Groovy’,’and’,’Grails’] assert str1 == ‘Groovy’ && str2 == ‘and’ && str3 == ‘Grails'[/groovy]

We can have types as part of the declaration [groovy] def (int a,String b) = [10,’someString’] [/groovy]

With method calls [groovy] def someMethod(){ [5,’Hello’] } def (int a,String b) = someMethod() [/groovy]

For more information see Multiple Assignments.

Ankur [email protected]

groovy multiple variable assignment

Grails 3.0- What’s New?

comments (1 “Multiple Variable Assignment in Groovy”)

' src=

great article

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

' src=

YOU MAY ALSO LIKE

  • Closure Delegate using Groovy “with” Method and decorating code with multiple assignments
  • StringJoiner in Java 8
  • Groovier way of sorting over multiple fields in a list of maps in groovy

groovy multiple variable assignment

Get latest articles straight to your inbox

  • CloudKeeper
  • DevOps as a Service
  • DevOps on AWS
  • DevOps Tools
  • DevOps Team
  • Python Development
  • Node.js Development
  • Grails Development
  • Java Development
  • MEAN Development
  • Grails Team
  • Node.js Team
  • Email Marketing
  • Search Engine Optimization
  • Social Listening
  • Web Analytics
  • Influencer Marketing
  • Content Marketing
  • Social Media Marketing
  • Creative Strategy
  • Digital Campaigns and Activations
  • Media planning and buying
  • Search Marketing
  • Digital Strategy
  • AEM Development
  • Drupal Development
  • iOS App Development
  • Android Development
  • Smart TV App Development
  • Hybrid Application Development
  • Mobility Team
  • AngularJS Development
  • React Native Development
  • React js Development
  • Software Product Engineering
  • Video Managed Services
  • Multiscreen Solutions
  • Offshore Software Development
  • Outsourced Software Product Development
  • Custom Software Development
  • Bespoke Software Development
  • Custom Web Application Development
  • Outsource Web Application Development
  • Offshore Development Center

Tips for writing a blog

Learn how to write a caption.

Groovy Language Documentation

Single-line comment, multiline comment, groovydoc comment, shebang line, 1.1.2. keywords, normal identifiers, quoted identifiers, single-quoted string, string concatenation, escaping special characters, unicode escape sequence, string interpolation, special case of interpolating closure expressions, interoperability with java, gstring and string hashcodes, triple-double-quoted string, special cases, dollar slashy string, string summary table.

  • Binary literal
  • Octal literal
  • Hexadecimal literal

Decimal literals

Underscore in literals, number type suffixes, the case of the division operator, the case of the power operator, 1.1.6. booleans, 1.1.7. lists, java-style array initialization, 1.1.9. maps, normal arithmetic operators, unary operators, assignment arithmetic operators, 1.2.2. relational operators, short-circuiting, bitwise operators, bit shift operators, not operator, ternary operator, elvis operator, elvis assignment operator, safe navigation operator, direct field access operator, method pointer operator, method reference operator, pattern operator, find operator, match operator, comparing find vs match operators, spreading method arguments, spread list elements, spread map elements, range operator, spaceship operator, subscript operator, safe index operator, membership operator, identity operator, coercion operator, diamond operator, call operator, 1.2.9. operator precedence, 1.2.10. operator overloading, 1.3.1. package names, default imports, simple import, star import, static import, static import aliasing, static star import, import aliasing, public static void main vs script, script class, primitive types, reference types, normal class, anonymous inner class, abstract class, inheritance, superclasses, positional parameters, named parameters, method definition.

  • Mixing named and positional parameters

Default arguments

Method selection algorithm, exception declaration.

  • Property naming conventions
  • Modifiers on a property
  • Annotations on a property
  • Split property definition with an explicit backing field
  • Explicit accessor methods

Annotation placement

Annotation member values, retention policy, closure annotation parameters, declaring meta-annotations, behavior of meta-annotations, meta-annotation parameters, handling duplicate annotations in meta-annotations, custom meta-annotation processors, public methods, abstract methods, private methods, final methods, the meaning of this, private fields, public fields, composition of behaviors, overriding default methods, simple inheritance, multiple inheritance, dynamic code, dynamic methods in a trait, default conflict resolution, user conflict resolution, implementing a trait at runtime, implementing multiple traits at once, semantics of super inside a trait, sam type coercion, differences with java 8 default methods, differences with mixins, static methods, properties and fields, inheritance of state gotchas, type constraints on traits, the @selftype annotation, differences with sealed annotation (incubating), compatibility with ast transformations, prefix and postfix operations, compact constructor, serializability, argument defaults, declarative tostring customization, obtaining a list of the record component values, obtaining a map of the record component values, obtaining the number of components in a record, obtaining the n th component from a record, deep immutability, obtaining the components of a record as a typed tuple, other differences to java, differences to java, defining a closure, closures as an object, calling a closure, normal parameters, implicit parameter, groovy closures vs lambda expressions, owner of a closure, delegate of a closure, delegation strategy, delegation strategy in the presence of metaprogramming, 1.5.4. closures in gstrings, 1.5.5. closure coercion, left currying, right currying, index based currying, memoization, composition, method pointers, variable definition, multiple assignment, overflow and underflow, object destructuring with multiple assignment.

  • switch / case
  • Classic for loop
  • Enhanced classic Java-style for loop
  • Multi-assignment in combination with for loop
  • for in loop
  • do/while loop

Exception handling

Try / catch / finally, multi-catch, arm try with resources, power assertion, labeled statements, object navigation, expression deconstruction, gpath for xml navigation, number promotion, assigning a closure to a sam type, calling a method accepting a sam type with a closure, closure to arbitrary type coercion, map to type coercion, string to enum coercion, custom type coercion, class literals vs variables and the as operator, optional parentheses, optional semicolons, optional return keyword, optional public keyword, boolean expressions, collections and arrays, iterators and enumerations, object references, customizing the truth with asboolean() methods, optional typing.

  • Activating type checking at compile time
  • Skipping sections

Type checking assignments

List and map constructors, method resolution.

  • Variables vs fields in type inference
  • Collection literal type inference
  • Least upper bound
  • instanceof inference
  • Flow typing
  • Advanced type inference
  • Return type inference
  • Explicit closure parameters
  • Parameters inferred from single-abstract method types
  • The @ClosureParams annotation

@DelegatesTo

Dynamic vs static, the @compilestatic annotation, key benefits, towards a smarter type checker, the extensions attribute, a dsl for type checking.

  • Support classes
  • Class nodes
  • Helping the type checker
  • Throwing an error
  • isXXXExpression
  • Virtual methods

Other useful methods

Precompiled type checking extensions, using @grab in a type checking extension, sharing or packaging type checking extensions, global type checking extensions, type checking extensions and @compilestatic, mixed mode compilation, transforming the ast in an extension, 2.1.1. groovy, the groovy command, 2.2.1. groovyc, the groovy compiler, 2.2.2. ant task, 2.2.3. gant, 2.2.4. gradle, the groovy eclipse maven plugin, 2.2.6. joint compilation, 2.2.7. android support, command-line options and arguments, simple expressions, evaluation result.

  • Define a Class
  • Use the Class
  • interpreterMode
  • show-last-result
  • sanitize-stack-trace

Setting a Preference

Listing preferences, clearing preferences (i.e. resetting to defaults).

  • $HOME/.groovy/groovysh.profile
  • $HOME/.groovy/groovysh.rc
  • $HOME/.groovy/groovysh.history

Custom commands

  • Problems loading the JLine DLL
  • Problems with Cygwin on Windows

2.3.2. GMavenPlus Maven Plugin

2.3.3. gradle groovysh plugin, 2.4.1. groovy : groovy console, 2.4.2. basics, running scripts, editing files, history and results, interrupting a script, 2.4.4. embedding the console, 2.4.5. visualizing script output results, 2.4.6. advanced debugging: ast browser, 2.4.7. advanced debugging: cst browser, 2.5.1. the groovydoc command line tool, required taskdef, <groovydoc> attributes, example #1 - <groovydoc> ant task, example #2 - executing <groovydoc> from groovy, custom groovydoc class, using the custom groovydoc task, 2.5.3. gmavenplus maven plugin, 2.6. ide integration, prerequisites, 3.1.2. maven repository, 3.1.3. sdkman (the software development kit manager), installation on windows, other distributions, source code, 3.1.5. install binary, 3.2.1. default imports, 3.2.2. multi-methods, 3.2.3. array initializers, 3.2.4. package scope visibility, 3.2.5. arm blocks, static inner classes, anonymous inner classes, creating instances of non-static inner classes, 3.2.7. lambda expressions and the method reference operator, 3.2.8. gstrings, 3.2.9. string and character literals, 3.2.10. behaviour of ==, numeric primitive optimisation with @compilestatic, positive/negative zero edge case, 3.2.12. conversions, 3.2.13. extra keywords, reading files, writing files, traversing file trees, data and objects, executing external processes, list literals, list as a boolean expression, iterating on a list.

  • Filtering and searching
  • Adding or removing elements
  • Set operations
  • Duplicating elements

Map literals

Map property notation, iterating on maps.

  • Keys, values and entries

GPath support

Spread operator, the star-dot `*.' operator, slicing with the subscript operator, enhanced collection methods, array literals, 3.3.4. working with legacy date/calendar types, formatting and parsing, addition and subtraction, multiplication and division, incrementing and decrementing, property notation, ranges, upto , and downto, combining date/time values, creating periods and durations, converting between legacy and jsr 310 types, configslurper, observable list, map and set, invokemethod, get/setproperty, get/setmetaclass, get/setattribute, methodmissing, propertymissing, static methodmissing, static propertymissing, groovyinterceptable, the default metaclass metaclassimpl.

  • Delegating metaclass
  • Magic package

Per instance metaclass

Constructors.

  • Static Methods
  • Borrowing Methods
  • Dynamic Method Names
  • Runtime Discovery
  • GroovyObject Methods
  • Overriding Static invokeMethod
  • Extending Interfaces

Extending existing classes

Instance methods, static methods, module descriptor, extension modules and classpath, compatibility with type checking.

  • @groovy.transform.ToString
  • @groovy.transform.EqualsAndHashCode
  • @groovy.transform.TupleConstructor
  • Implementation Details
  • Immutability support
  • Customization options
  • @groovy.transform.MapConstructor
  • @groovy.transform.Canonical
  • @groovy.transform.InheritConstructors
  • @groovy.lang.Category
  • @groovy.transform.IndexedProperty
  • @groovy.lang.Lazy
  • @groovy.lang.Newify
  • @groovy.transform.Sortable
  • @groovy.transform.builder.Builder
  • @groovy.transform.AutoImplement
  • @groovy.transform.NullCheck
  • @groovy.transform.BaseScript
  • @groovy.lang.Delegate
  • @groovy.transform.Immutable
  • @groovy.transform.ImmutableBase
  • @groovy.transform.PropertyOptions
  • @groovy.transform.VisibilityOptions
  • @groovy.transform.ImmutableOptions
  • @groovy.transform.KnownImmutable
  • @groovy.transform.Memoized
  • @groovy.transform.TailRecursive
  • @groovy.lang.Singleton
  • @groovy.lang.Mixin
  • @groovy.util.logging.Log
  • @groovy.util.logging.Commons
  • @groovy.util.logging.Log4j
  • @groovy.util.logging.Log4j2
  • @groovy.util.logging.Slf4j
  • @groovy.util.logging.PlatformLog
  • @groovy.transform.Synchronized
  • @groovy.transform.WithReadLock and @groovy.transform.WithWriteLock
  • @groovy.transform.AutoClone
  • @groovy.transform.AutoExternalize
  • @groovy.transform.ThreadInterrupt
  • @groovy.transform.TimedInterrupt
  • @groovy.transform.ConditionalInterrupt
  • @groovy.transform.Field
  • @groovy.transform.PackageScope
  • @groovy.transform.Final
  • @groovy.transform.AutoFinal
  • @groovy.transform.AnnotationCollector
  • @groovy.transform.TypeChecked
  • @groovy.transform.CompileStatic
  • @groovy.transform.CompileDynamic
  • @groovy.lang.DelegatesTo
  • @groovy.transform.SelfType
  • @groovy.beans.Bindable
  • @groovy.beans.ListenerList
  • @groovy.beans.Vetoable
  • @groovy.test.NotYetImplemented
  • @groovy.transform.ASTTest
  • @groovy.lang.Grab
  • @groovy.lang.GrabConfig
  • @groovy.lang.GrabExclude
  • @groovy.lang.GrabResolver
  • @groovy.lang.Grapes

Compilation phases guide

Local transformations, global transformations.

  • AbstractASTTransformation
  • ClassCodeExpressionTransformer

Introduction

  • Statements and expressions
  • Variable substitution
  • @Macro methods
  • Separating source trees
  • Debugging AST transformations

External references

Add a dependency, specify additional repositories, maven classifiers, excluding transitive dependencies, jdbc drivers, using grape from the groovy shell, proxy settings, 3.5.2. detail, multiple grape annotations, grab(hashmap) parameters, arguments map arguments, command line tool, repository directory, customize ivy settings, more examples, 3.6.1. introduction, power assertions, map coercion, closure coercion, mockfor and stubfor, expando meta-class (emc), iterable#combinations, iterable#eachcombination, test code coverage, assertion methods, shouldfail methods, notyetimplemented method, specifications, a geb script, 3.7. tune parsing performance of parrot parser, parser variants, formatted output, connecting with a datasource, connecting using @grab, creating tables, creating/inserting data, reading rows, updating rows, deleting rows, working with transactions, using batches, performing pagination, fetching metadata, named and named-ordinal parameters, stored procedures, 3.9.5. using datasets.

  • Iterable Data Source
  • Stream Data Source
  • Array Data Source
  • GINQ Result Set Data Source
  • Aggregate Functions
  • Nested GINQ in from clause
  • Nested GINQ in where clause
  • Nested GINQ in select clause
  • rank , denseRank , percentRank , cumeDist and ntile
  • lead and lag
  • firstValue , lastValue and nthValue
  • min , max , count , sum , avg , median , stdev , stdevp , var , varp and agg

List Comprehension

Query & update, alternative for with clause, alternative for case-when, parallel querying, customize ginq, optimize ginq, generate multiplication table, more examples, xmlparser and xmlslurper, domcategory, simply traversing the tree, flexible navigation with children (*), depthfirst (**) and breadthfirst, markupbuilder, streamingmarkupbuilder, markupbuilderhelper, domtogroovy, adding nodes, modifying / removing nodes, 3.14.1. applying @invariant, @requires and @ensures, 3.14.2. more features, 3.14.3. the stack example, 3.15. scripting ant tasks, 3.16.1. <groovy>, 3.16.2. required taskdef, 3.16.3. <groovy> attributes, <classpath>, <arg>, 3.16.5. available bindings, 3.16.6. examples, description, <groovyc> attributes, <groovyc> nested elements, joint compilation, 3.18.1. introduction, 3.18.2. template framework, advanced usage note, 3.18.4. streamingtemplateengine, 3.18.5. gstringtemplateengine, 3.18.6. xmltemplateengine, support methods, creation of a template engine, configuration options, automatic formatting, automatic escaping.

  • Strings containing markup

Internationalization

Custom template classes, optional type checking, alternative declaration of types, performance of type checked templates, 3.18.8. other solutions, 3.19.1. implicit variables, 3.19.2. setting up groovlets, multiple sources, sharing data between a script and the application, custom script class, groovyclassloader, groovyscriptengine, compilationunit, 3.20.2. jsr 223 javax.script api, 3.21.1. command chains, 3.21.2. operator overloading, the script class, the @basescript annotation, alternate abstract method, 3.21.4. adding properties to numbers, explaining delegation strategy at compile time, simple delegation, delegate to parameter, multiple closures, delegating to a generic type, delegating to an arbitrary type, import customizer, ast transformation customizer, secure ast customizer, source aware customizer, inlining a customizer, multiple customizers, configscript example: static compilation by default, configscript example: setting system properties, ast transformations, 3.21.7. custom type checking extensions, staxbuilder, nodebuilder, jsonbuilder, streamingjsonbuilder, swingbuilder.

  • Using Annotations and an interface
  • Using Annotations and an instance
  • Using Annotations and a script
  • Options with arguments
  • Specifying a type
  • Custom parsing of the argument String
  • Options with multiple arguments
  • Types and multiple arguments
  • Setting a default value
  • Use with TypeChecked
  • Apache Commons CLI

ObjectGraphBuilder

Filetreebuilder, buildersupport, factorybuildersupport, 3.22.1. introduction, 3.22.2. monitoring the jvm, 3.22.3. monitoring tomcat, 3.22.4. oc4j example, 3.22.5. weblogic example, 3.22.6. spring example, java.lang.securityexception, instantiating jmxbuilder, connector server, connector client, implicit vs explicit descriptors, the jmxbuilder.export() node, jmxbuilder.export() syntax, integration with groovymbean class.

  • JConsole view of Exported Bean

JmxBuilder.bean() Syntax

Bean() node - specifying mbean objectname, export all attributes with wildcard "*", export attribute list, export attribute with explicit descriptors, export all constructors with "*", export constructors using parameter descriptor, export constructor with explicit descriptors, export all operations with "*", export operation list, export operations by signature, export operations with explicit descriptors, embedding descriptor, timer node syntax, exporting a timer, timer period.

  • Parameterless
  • With Event Parameter

Handling Attribute onChange Event

Attribute onchange event object, handling operation oncall event, operation oncall event object, listening to jmx events, listener node syntax, emitter syntax, declare the emitter, broadcast event, sending event objects, 3.22.9. further jmx information, 3.23. creating swing uis, 3.24. security, delegation example, inheritance example, adapting using closures, adapting using the expandometaclass, null checking example, validation example, example using traditional classes, example using simplifying strategies, when not to use, going further, example with traditional classes, simplifying variations, traditional example, simplifying with closures or lambdas, a touch of dynamic behaviour, runtime behaviour embellishment, more dynamic decorating, decorating with an interceptor, decorating with java.lang.reflect.proxy, decorating with spring, asynchronous decorators using gpars, implement delegation pattern using expandometaclass, implement delegation pattern using @delegate annotation, iterator pattern, a touch of formalism, benefits of monoids, working with non-monoids, simple example, tree example, @bindable and @vetoable, example: the classic java singleton, example: singleton via metaprogramming, guice example, spring example, further information, variation 1: leveraging interface-oriented design, variation 2: extract state pattern logic, variation 3: bring on the dsl, example using traditional class hierarchy, example using closures, example using lambdas, example with simplifying strategies.

  • When to use this
  • What happens if we add a new type?
  • What if we want to have different iteration patterns?
  • Make it Groovy

Further Information

3.25.2. references, 4.1. contributors, 4.2. license.

Groovy…​

is an agile and dynamic language for the Java Virtual Machine

builds upon the strengths of Java but has additional power features inspired by languages like Python, Ruby and Smalltalk

makes modern programming features available to Java developers with almost-zero learning curve

provides the ability to statically type check and statically compile your code for robustness and performance

supports Domain-Specific Languages and other compact syntax so your code becomes easy to read and maintain

makes writing shell and build scripts easy with its powerful processing primitives, OO abilities and an Ant DSL

increases developer productivity by reducing scaffolding code when developing web, GUI, database or console applications

simplifies testing by supporting unit testing and mocking out-of-the-box

seamlessly integrates with all existing Java classes and libraries

compiles straight to Java bytecode so you can use it anywhere you can use Java

1. Groovy Language Specification

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

1.1.1. Comments

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.

A multiline comment starts with /* and can be found at any position in the line. The characters following /* will be considered part of the comment, including new line characters, up to the first */ closing the comment. Multiline comments can thus be put at the end of a statement, or even inside a statement.

Similarly to multiline comments, Groovydoc comments are multiline, but start with /** and end with */ . Lines following the first Groovydoc comment line can optionally start with a star * . Those comments are associated with:

type definitions (classes, interfaces, enums, annotations),

fields and properties definitions

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.

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.

Runtime Groovydoc is disabled by default. It can be enabled by adding JVM option

The Runtime Groovydoc starts with /**@ and ends with */ , for example:

Get the runtime groovydoc for class
Get the runtime groovydoc for method

Beside the single-line comment, there is a special line comment, often called the shebang line understood by UNIX systems which allows scripts to be run directly from the command-line, provided you have installed the Groovy distribution and the groovy command is available on the PATH .

The character must be the first character of the file. Any indentation would yield a compilation error.

Groovy has the following reserved keywords:

Table 1. Reserved Keywords

abstract

assert

break

case

catch

class

const

continue

def

default

do

else

enum

extends

final

finally

for

goto

if

implements

import

instanceof

interface

native

new

null

non-sealed

package

public

protected

private

return

static

strictfp

super

switch

synchronized

this

threadsafe

throw

throws

transient

try

while

Of these, const , goto , strictfp , and threadsafe are not currently in use.

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 scenarios where having "verbs" and "nouns" with the same name as keywords may be desirable.

In addition, Groovy has the following contextual keywords:

Table 2. Contextual Keywords

as

in

permits

record

sealed

trait

var

yields

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

Table 3. Other reserved words

null

true

false

boolean

char

byte

short

int

long

float

double

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 .

1.1.3. Identifiers

Identifiers start with a letter, a dollar or an underscore. They cannot start with a number.

A letter can be in the following ranges:

'a' to 'z' (lowercase ascii letter)

'A' to 'Z' (uppercase ascii letter)

'\u00C0' to '\u00D6'

'\u00D8' to '\u00F6'

'\u00F8' to '\u00FF'

'\u0100' to '\uFFFE'

Then following characters can contain letters and numbers.

Here are a few examples of valid identifiers (here, variable names):

But the following ones are invalid identifiers:

All keywords are also valid identifiers when following a dot:

Quoted identifiers appear after the dot of a dotted expression. For instance, the name part of the person.name expression can be quoted with person."name" or person.'name' . This is particularly interesting when certain identifiers contain illegal characters that are forbidden by the Java Language Specification, but which are allowed by Groovy when quoted. For example, characters like a dash, a space, an exclamation mark, etc.

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:

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:

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

Single-quoted strings are a series of characters surrounded by single quotes:

Single-quoted strings are plain and don’t support interpolation.

All the Groovy strings can be concatenated with the + operator:

Triple-single-quoted string

Triple-single-quoted strings are a series of characters surrounded by triplets of single quotes:

Triple-single-quoted strings are plain and don’t support interpolation.

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.

When creating a string as follows:

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:

You can escape single quotes with the backslash character to avoid terminating the string literal:

And you can escape the escape character itself with a double backslash:

Some special characters also use the backslash as escape character:

Escape sequence Character

\b

backspace

\f

formfeed

\n

newline

\r

carriage return

\s

single space

\t

tabulation

\\

backslash

\'

single quote within a single-quoted string (and optional for triple-single-quoted and double-quoted strings)

\"

double quote within a double-quoted string (and optional for triple-double-quoted and single-quoted strings)

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.

For example, the Euro currency symbol can be represented with:

Double-quoted string

Double-quoted strings are a series of characters surrounded by double quotes:

Double-quoted strings are plain if there’s no interpolated expression, but are instances if interpolation is present.
To escape a double quote, you can use the backslash character: "A double quote: \"".

Any Groovy expression can be interpolated in all string literals, apart from single and triple-single-quoted strings. Interpolation is the act of replacing a placeholder in the string with its value upon evaluation of the string. The placeholder expressions are surrounded by ${} . The curly braces may be omitted for unambiguous dotted expressions, i.e. we can use just a $ prefix in those cases. If the GString is ever passed to a method taking a String, the expression value inside the placeholder is evaluated to its string representation (by calling toString() on that expression) and the resulting String is passed to the method.

Here, we have a string with a placeholder referencing a local variable:

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

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:

The following statement will throw a groovy.lang.MissingPropertyException because Groovy believes you’re trying to access the toString property of that number, which doesn’t exist:

You can think of as being interpreted by the parser as .

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:

So far, we’ve seen we could interpolate arbitrary expressions inside the ${} placeholder, but there is a special case and notation for closure expressions. When the placeholder contains an arrow, ${→} , the expression is actually a closure expression — you can think of it as a closure with a dollar prepended in front of it:

The closure is a parameterless closure which doesn’t take arguments.
Here, the closure takes a single argument, to which you can append content with the leftShift operator. In either case, both placeholders are embedded closures.

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.

Let’s consider the following sample:

We define a variable containing that we then interpolate within two GStrings, as an expression in and as a closure in .
We expect the resulting string to contain the same string value of 1 for .
Similarly for
Then we change the value of the variable to a new number
With a plain interpolated expression, the value was actually bound at the time of creation of the GString.
But with a closure expression, the closure is called upon each coercion of the GString into String, resulting in an updated string containing the new number value.
An embedded closure expression taking more than one parameter will generate an exception at runtime. Only closures with zero or one parameter are allowed.

When a method (whether implemented in Java or Groovy) expects a java.lang.String , but we pass a groovy.lang.GString instance, the toString() method of the GString is automatically and transparently called.

We create a GString variable
We double-check it’s an instance of the GString
We then pass that GString to a method taking a String as parameter
The signature of the method explicitly says its sole parameter is a String
We also verify that the parameter is indeed a String and not a GString.

Although interpolated strings can be used in lieu of plain Java strings, they differ with strings in a particular way: their hashCodes are different. Plain Java strings are immutable, whereas the resulting String representation of a GString can vary, depending on its interpolated values. Even for the same resulting string, GStrings and Strings don’t have the same hashCode.

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.

The map is created with an initial pair whose key is a GString
When we try to fetch the value with a String key, we will not find it, as Strings and GString have different hashCode values

Triple-double-quoted strings behave like double-quoted strings, with the addition that they are multiline, like the triple-single-quoted strings.

Neither double quotes nor single quotes need be escaped in triple-double-quoted strings.

Slashy string

Beyond the usual quoted strings, Groovy offers slashy strings, which use / as the opening and closing delimiter. Slashy strings are particularly useful for defining regular expressions and patterns, as there is no need to escape backslashes.

Example of a slashy string:

Only forward slashes need to be escaped with a backslash:

Slashy strings are multiline:

Slashy strings can be thought of as just another way to define a GString but with different escaping rules. They hence support interpolation:

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:

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.

Dollar slashy strings are multiline GStrings delimited with an opening $/ and a closing /$ . The escaping character is the dollar sign, and it can escape another dollar, or a forward slash. Escaping for the dollar and forward slash characters is only needed where conflicts arise with the special use of those characters. The characters $foo would normally indicate a GString placeholder, so those four characters can be entered into a dollar slashy string by escaping the dollar, i.e. $$foo . Similarly, you will need to escape a dollar slashy closing delimiter if you want it to appear in your string.

Here are a few examples:

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

String name

String syntax

Interpolated

Multiline

Escape character

Single-quoted

Triple-single-quoted

Double-quoted

Triple-double-quoted

Slashy

Dollar slashy

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:

by being explicit when declaring a variable holding the character by specifying the type
by using type coercion with the operator
by using a cast to char operation
The first option is interesting when the character is held in a variable, while the other two ( and ) are more interesting when a char value must be passed as argument of a method call.

1.1.5. Numbers

Groovy supports different kinds of integral literals and decimal literals, backed by the usual Number types of Java.

Integral literals

The integral literal types are the same as in Java:

java.math.BigInteger

You can create integral numbers of those types with the following declarations:

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.

For positive numbers:

As well as for negative numbers:

Alternative non-base 10 representations

Numbers can also be represented in binary, octal, hexadecimal and decimal bases.

Binary numbers start with a 0b prefix:

Octal numbers are specified in the typical format of 0 followed by octal digits.

Hexadecimal numbers are specified in the typical format of 0x followed by hex digits.

The decimal literal types are the same as in Java:

java.math.BigDecimal

You can create decimal numbers of those types with the following declarations:

Decimals can use exponents, with the e or E exponent letter, followed by an optional sign, and an integral number representing the exponent:

Conveniently for exact decimal number calculations, Groovy chooses java.math.BigDecimal as its decimal number type. In addition, both float and double are supported, but require an explicit type declaration, type coercion or suffix. Even if BigDecimal is the default for decimal numbers, such literals are accepted in methods or closures taking float or double as parameter types.

Decimal numbers can’t be represented using a binary, octal or hexadecimal representation.

When writing long literal numbers, it’s harder on the eye to figure out how some numbers are grouped together, for example with groups of thousands, of words, etc. By allowing you to place underscore in number literals, it’s easier to spot those groups:

We can force a number (including binary, octals and hexadecimals) to have a specific type by giving a suffix (see table below), either uppercase or lowercase.

Type Suffix

BigInteger

or

Long

or

Integer

or

BigDecimal

or

Double

or

Float

or

Math operations

Although operators are covered in more detail elsewhere, it’s important to discuss the behavior of math operations and what their resulting types are.

Division and power binary operations aside (covered below),

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

binary operations involving BigDecimal with byte , char , short , int and BigInteger result in BigDecimal

binary operations between float , double and BigDecimal result in double

binary operations between two BigDecimal result in BigDecimal

The following table summarizes those rules:

byte char short int long BigInteger float double BigDecimal

int

int

int

int

long

BigInteger

double

double

BigDecimal

int

int

int

long

BigInteger

double

double

BigDecimal

int

int

long

BigInteger

double

double

BigDecimal

int

long

BigInteger

double

double

BigDecimal

long

BigInteger

double

double

BigDecimal

BigInteger

double

double

BigDecimal

double

double

double

double

double

BigDecimal

Thanks to Groovy’s operator overloading, the usual arithmetic operators work as well with and , unlike in Java where you have to use explicit methods for operating on those numbers.

The division operators / (and /= for division and assignment) produce a double result if either operand is a float or double , and a BigDecimal result otherwise (when both operands are any combination of an integral type short , char , byte , int , long , BigInteger or 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 of the maximum of the two operands' precision plus an extra precision of 10, and a scale of the maximum of 10 and the maximum of the operands' scale.

For integer division like in Java, you should use the method, as Groovy doesn’t provide a dedicated integer division operator symbol.

The power operation is represented by the ** operator, with two parameters: the base and the exponent. The result of the power operation depends on its operands, and the result of the operation (in particular if the result can be represented as an integral value).

The following rules are used by Groovy’s power operation to determine the resulting type:

If the exponent is a decimal value

if the result can be represented as an Integer , then return an Integer

else if the result can be represented as a Long , then return a Long

otherwise return a Double

If the exponent is an integral value

if the exponent is strictly negative, then return an Integer , Long or Double if the result value fits in that type

if the exponent is positive or zero

if the base is a BigDecimal , then return a BigDecimal result value

if the base is a BigInteger , then return a BigInteger result value

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

We can illustrate those rules with a few examples:

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 .

Boolean values can be stored in variables, assigned into fields, just like any other data type:

true and false are the only two primitive boolean values. But more complex boolean expressions can be represented using logical operators .

In addition, Groovy has special rules (often referred to as Groovy Truth ) for coercing non-boolean objects to a boolean value.

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 we assign that list into a variable
The list is an instance of Java’s interface
The size of the list can be queried with the method, and shows our list contains 3 elements

In the above example, we used a homogeneous list, but you can also create lists containing values of heterogeneous types:

Our list here contains a number, a string and a boolean value

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:

We use coercion with the operator to explicitly request a implementation
We can say that the variable holding the list literal is of type

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:

Access the first element of the list (zero-based counting)
Access the last element of the list with a negative index: -1 is the first element from the end of the list
Use an assignment to set a new value for the third element of the list
Use the leftShift operator to append an element at the end of the list
Access two elements at once, returning a new list containing those two elements
Use a range to access a range of values from the list, from a start to an end element position

As lists can be heterogeneous in nature, lists can also contain other lists to create multidimensional lists:

Define a list of numbers
Access the second element of the top-most list, and the first element of the inner list

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

Define an array of strings using explicit variable type declaration
Assert that we created an array of strings
Create an array of ints with the operator
Assert that we created an array of primitive ints

You can also create multi-dimensional arrays:

You can define the bounds of a new array
Or declare an array without specifying its bounds

Access to elements of an array follows the same notation as for lists:

Retrieve the first element of the array
Set the value of the third element of the array to a new value

Groovy has always supported literal list/array definitions using square brackets and has avoided Java-style curly braces so as not to conflict with closure definitions. In the case where the curly braces come immediately after an array type declaration however, there is no ambiguity with closure definitions, so Groovy 3 and above support that variant of the Java array initialization expression.

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.

We define a map of string color names, associated with their hexadecimal-coded html colors
We use the subscript notation to check the content associated with the key
We can also use the property notation to assert the color green’s hexadecimal representation
Similarly, we can use the subscript notation to add a new key/value pair
Or the property notation, to add the color
When using names for the keys, we actually define string keys in the map.
Groovy creates maps that are actually instances of .

If you try to access a key which is not present in the map:

You will retrieve a null result.

In the examples above, we used string keys, but you can also use values of other types as keys:

Here, we used numbers as keys, as numbers can unambiguously be recognized as numbers, so Groovy will not create a string key like in our previous examples. But consider the case you want to pass a variable in lieu of the key, to have the value of that variable become the key:

The associated with the name will actually be the string, not the value associated with the variable
The map doesn’t contain the key
Instead, the map contains a 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:

This time, we surround the variable with parentheses, to instruct the parser we are passing a variable rather than defining a string key
The map does contain the key
But the map doesn’t contain the key as before

1.2. Operators

This chapter covers the operators of the Groovy programming language.

1.2.1. Arithmetic operators

Groovy supports the usual familiar arithmetic operators you find in mathematics and in other programming languages like Java. All the Java arithmetic operators are supported. Let’s go through them in the following examples.

The following binary arithmetic operators are available in Groovy:

Operator Purpose Remarks

addition

subtraction

multiplication

division

Use for integer division, and see the section about for more information on the return type of the division.

remainder

power

See the section about for more information on the return type of the operation.

Here are a few examples of usage of those operators:

The + and - operators are also available as unary operators:

Note the usage of parentheses to surround an expression to apply the unary minus to that surrounded expression.

In terms of unary arithmetics operators, the ++ (increment) and -- (decrement) operators are available, both in prefix and postfix notation:

The postfix increment will increment after the expression has been evaluated and assigned into
The postfix decrement will decrement after the expression has been evaluated and assigned into
The prefix increment will increment before the expression is evaluated and assigned into
The prefix decrement will decrement before the expression is evaluated and assigned into

For the unary not operator on Booleans, see Conditional operators .

The binary arithmetic operators we have seen above are also available in an assignment form:

Let’s see them in action:

Relational operators allow comparisons between objects, to know if two objects are the same or different, or if one is greater than, less than, or equal to the other.

The following operators are available:

Operator Purpose

equal

different

less than

less than or equal

greater than

greater than or equal

identical (Since Groovy 3.0.0)

not identical (Since Groovy 3.0.0)

Here are some examples of simple number comparisons using these operators:

Both === and !== are supported which are the same as calling the is() method, and negating a call to the is() method respectively.

1.2.3. Logical operators

Groovy offers three logical operators for boolean expressions:

&& : logical "and"

|| : logical "or"

! : logical "not"

Let’s illustrate them with the following examples:

"not" false is true
true "and" true is true
true "or" false is true

The logical "not" has a higher priority than the logical "and".

Here, the assertion is true (as the expression in parentheses is false), because "not" has a higher precedence than "and", so it only applies to the first "false" term; otherwise, it would have applied to the result of the "and", turned it into true, and the assertion would have failed

The logical "and" has a higher priority than the logical "or".

Here, the assertion is true, because "and" has a higher precedence than "or", therefore the "or" is executed last and returns true, having one true argument; otherwise, the "and" would have executed last and returned false, having one false argument, and the assertion would have failed

The logical || operator supports short-circuiting: if the left operand is true, it knows that the result will be true in any case, so it won’t evaluate the right operand. The right operand will be evaluated only if the left operand is false.

Likewise for the logical && operator: if the left operand is false, it knows that the result will be false in any case, so it won’t evaluate the right operand. The right operand will be evaluated only if the left operand is true.

We create a function that sets the flag to true whenever it’s called
In the first case, after resetting the called flag, we confirm that if the left operand to is true, the function is not called, as short-circuits the evaluation of the right operand
In the second case, the left operand is false and so the function is called, as indicated by the fact our flag is now true
Likewise for , we confirm that the function is not called with a false left operand
But the function is called with a true left operand

1.2.4. Bitwise and bit shift operators

Groovy offers four bitwise operators:

& : bitwise "and"

| : bitwise "or"

^ : bitwise "xor" (exclusive "or")

~ : bitwise negation

Bitwise operators can be applied on arguments which are of type byte , short , int , long , or BigInteger . If one of the arguments is a BigInteger , the result will be of type BigInteger ; otherwise, if one of the arguments is a long , the result will be of type long ; otherwise, the result will be of type int :

bitwise and
bitwise and returns common bits
bitwise or
bitwise or returns all '1' bits
setting a mask to check only the last 8 bits
bitwise exclusive or on self returns 0
bitwise exclusive or
bitwise negation

It’s worth noting that the internal representation of primitive types follow the Java Language Specification . In particular, primitive types are signed, meaning that for a bitwise negation, it is always good to use a mask to retrieve only the necessary bits.

In Groovy, bitwise operators are overloadable , meaning that you can define the behavior of those operators for any kind of object.

Groovy offers three bit shift operators:

<< : left shift

>> : right shift

>>> : right shift unsigned

All three operators are applicable where the left argument is of type byte , short , int , or long . The first two operators can also be applied where the left argument is of type BigInteger . If the left argument is a BigInteger , the result will be of type BigInteger ; otherwise, if the left argument is a long , the result will be of type long ; otherwise, the result will be of type int :

method used instead of to confirm result type

In Groovy, bit shift operators are overloadable , meaning that you can define the behavior of those operators for any kind of object.

1.2.5. Conditional operators

The "not" operator is represented with an exclamation mark ( ! ) and inverts the result of the underlying boolean expression. In particular, it is possible to combine the not operator with the Groovy truth :

the negation of is
'foo' is a non-empty string, evaluating to , so negation returns
'' is an empty string, evaluating to , so negation returns

The ternary operator is a shortcut expression that is equivalent to an if/else branch assigning some value to a variable.

Instead of:

You can write:

The ternary operator is also compatible with the Groovy truth , so you can make it even simpler:

The "Elvis operator" is a shortening of the ternary operator. One instance of where this is handy is for returning a 'sensible default' value if an expression resolves to false -ish (as in Groovy truth ). A simple example might look like this:

with the ternary operator, you have to repeat the value you want to assign
with the Elvis operator, the value, which is tested, is used if it is not -ish

Usage of the Elvis operator reduces the verbosity of your code and reduces the risks of errors in case of refactorings, by removing the need to duplicate the expression which is tested in both the condition and the positive return value.

Groovy 3.0.0 introduces the Elvis operator, for example:

1.2.6. Object operators

The Safe Navigation operator is used to avoid a NullPointerException . Typically 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. To avoid this, the safe navigation operator will simply return null instead of throwing an exception, like so:

will return a instance
use of the null-safe operator prevents from a
result is

Normally in Groovy, when you write code like this:

public field
a getter for that returns a custom string
calls the getter

The user.name call triggers a call to the property of the same name, that is to say, here, to the getter for name . If you want to retrieve the field instead of calling the getter, you can use the direct field access operator:

use of forces usage of the field instead of the getter

The method pointer operator ( .& ) can be used to store a reference to a method in a variable, in order to call it later:

the variable contains a
we store a reference to the method on the instance inside a variable named
can be called like a regular method
we can check that the result is the same as if we had called it directly on

There are multiple advantages in using method pointers. First of all, the type of such a method pointer is a groovy.lang.Closure , so it can be used in any place a closure would be used. In particular, it is suitable to convert an existing method for the needs of the strategy pattern:

the method takes each element of the list and calls the closure on them, returning a new list
we define a function that takes a and returns a
we create a method pointer on that function
we create the list of elements we want to collect the descriptors
the method pointer can be used where a was expected

Method pointers are bound by the receiver and a method name. Arguments are resolved at runtime, meaning that if you have multiple methods with the same name, the syntax is not different, only resolution of the appropriate method to be called will be done at runtime:

define an overloaded method accepting a as an argument
define an overloaded method accepting an as an argument
create a single method pointer on , without specifying argument types
using the method pointer with a calls the version of
using the method pointer with an calls the version of

To align with Java 8 method reference expectations, in Groovy 3 and above, you can use new as the method name to obtain a method pointer to the constructor:

Also in Groovy 3 and above, you can obtain a method pointer to an instance method of a class. This method pointer takes an additional parameter being the receiver instance to invoke the method on:

For backwards compatibility, any static methods that happen to have the correct parameters for the call will be given precedence over instance methods for this case.

The Parrot parser in Groovy 3+ supports the Java 8+ method reference operator. The method reference operator ( :: ) can be used to reference a method or constructor in contexts expecting a functional interface. This overlaps somewhat with the functionality provided by Groovy’s method pointer operator. Indeed, for dynamic Groovy, the method reference operator is just an alias for the method pointer operator. For static Groovy, the operator results in bytecode similar to the bytecode that Java would produce for the same context.

Some examples highlighting various supported method reference cases are shown in the following script:

class instance method reference: add(BigInteger val) is an instance method in BigInteger
object instance method reference: add(BigInteger val) is an instance method for object 3G
class static method reference: valueOf(long val) is a static method for class BigInteger
object static method reference: valueOf(long val) is a static method for object 3G (some consider this bad style in normal circumstances)

Some examples highlighting various supported constructor reference cases are shown in the following script:

class constructor reference
array constructor reference

1.2.7. Regular expression operators

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

while in general, you find the pattern operator with an expression in a slashy-string, it can be used with any kind of String in Groovy:

using single quote strings
using double quotes strings
the dollar-slashy string lets you use slashes and the dollar sign without having to escape them
you can also use a GString!
While you can use most String forms with the Pattern, Find and Match operators, we recommend using the slashy string most of the time to save having to remember the otherwise needed escaping requirements.

Alternatively to building a pattern, you can use the find operator =~ to directly create a java.util.regex.Matcher instance:

creates a matcher against the variable, using the pattern on the right hand side
the return type of is a
equivalent to calling

Since a Matcher coerces to a boolean by calling its find method, the =~ operator is consistent with the simple use of Perl’s =~ operator, when it appears as a predicate (in if , ?: , etc.). When the intent is to iterate over matches of the specified pattern (in while , etc.) call find() directly on the matcher or use the iterator DGM.

The match operator ( ==~ ) is a slight variation of the find operator, that does not return a Matcher but a boolean and requires a strict match of the input string:

matches the subject with the regular expression, but match must be strict
the return type of is therefore a
equivalent to calling

Typically, the match operator is used when the pattern involves a single exact match, otherwise the find operator might be more useful.

equivalent, but explicit ^ and $ are discouraged since they aren’t needed
no match because of leading space
one match
^ and $ indicate exact match required
zero matches
one match, greedily starting at first word
one match, ignores leading space
two matches

1.2.8. Other operators

The Spread-dot Operator ( *. ), often abbreviated to just Spread Operator, is used to invoke an action on all items of an aggregate object. It is equivalent to calling the action on each item and collecting the result into a list:

build a list of items. The list is an aggregate of objects.
call the spread operator on the list, accessing the property of each item
returns a list of strings corresponding to the collection of items

The expression cars*.make is equivalent to cars.collect{ it.make } . Groovy’s GPath notation allows a short-cut when the referenced property isn’t a property of the containing list, in that case it is automatically spread. In the previously mentioned case, the expression cars.make can be used, though retaining the explicit spread-dot operator is often recommended.

The spread operator is null-safe, meaning that if an element of the collection is null, it will return null instead of throwing a NullPointerException :

build a list for which one of the elements is
using the spread operator will throw a
the receiver might also be null, in which case the return value is

The spread operator can be used on any class which implements the Iterable interface:

Use multiple invocations of the spread-dot operator (here cars*.models*.name ) when working with aggregates of data structures which themselves contain aggregates:

Consider using the collectNested DGM method instead of the spread-dot operator for collections of collections:

There may be situations when the arguments of a method call can be found in a list that you need to adapt to the method arguments. In such situations, you can use the spread operator to call the method. For example, imagine you have the following method signature:

then if you have the following list:

you can call the method without having to define intermediate variables:

It is even possible to mix normal arguments with spread ones:

When used inside a list literal, the spread operator acts as if the spread element contents were inlined into the list:

is a list
we want to insert the contents of the list directly into without having to call
the contents of has been inlined into

The spread map operator works in a similar manner as the spread list operator, but for maps. It allows you to inline the contents of a map into another map literal, like in the following example:

is the map that we want to inline
we use the notation to spread the contents of into
contains all the elements of

The position of the spread map operator is relevant, like illustrated in the following example:

is the map that we want to inline
we use the notation to spread the contents of into , but redefine the key spreading
contains all the expected keys, but was redefined

Groovy supports the concept of ranges and provides a notation ( .. ) to create ranges of objects:

a simple range of integers, stored into a local variable
an , with inclusive bounds
an , with exclusive upper bound
an , with exclusive lower bound
an , with exclusive lower and upper bounds
a implements the interface
meaning that you can call the method on it

Ranges implementation is lightweight, meaning that only the lower and upper bounds are stored. You can create a range from any Comparable object that has next() and previous() methods to determine the next / previous item in the range. For example, you can create a range of characters this way:

The spaceship operator ( <=> ) delegates to the compareTo method:

The subscript operator is a shorthand notation for getAt or putAt , depending on whether you find it on the left hand side or the right hand side of an assignment:

can be used instead of
if on left hand side of an assignment, will call
also supports ranges
so does
the list is mutated

The subscript operator, in combination with a custom implementation of getAt / putAt is a convenient way for destructuring objects:

the class defines a custom implementation
the class defines a custom implementation
create a sample user
using the subscript operator with index 0 allows retrieving the user id
using the subscript operator with index 1 allows retrieving the user name
we can use the subscript operator to write to a property thanks to the delegation to
and check that it’s really the property which was changed

Groovy 3.0.0 introduces safe indexing operator, i.e. ?[] , which is similar to ?. . For example:

The membership operator ( in ) is equivalent to calling the isCase method. In the context of a List , it is equivalent to calling contains , like in the following example:

equivalent to calling or
membership negation equivalent to calling or

In Groovy, using == to test equality is different from using the same operator in Java. In Groovy, it is calling equals . If you want to compare reference equality, you should use is like in the following example:

Create a list of strings
Create another list of strings containing the same elements
using , we test object equality, equivalent to in Java
using , we can check that references are distinct, equivalent to in Java
using or (supported and recommended since Groovy 3.0.0), we can also check whether references are distinct or not, equivalent to and in Java

The coercion operator ( as ) is a variant of casting. Coercion converts object from one type to another without them being compatible for assignment. Let’s take an example:

is not assignable to an , so it will produce a at runtime

This can be fixed by using coercion instead:

is not assignable to an , but use of will it to an

When an object is coerced into another, unless the target type is the same as the source type, coercion will return a new object. The rules of coercion differ depending on the source and target types, and coercion may fail if no conversion rules are found. Custom conversion rules may be implemented thanks to the asType method:

the class defines a custom conversion rule from to
we create an instance of
we coerce the instance into an
the target is an instance of
the target is not an instance of anymore

The diamond operator ( <> ) is a syntactic sugar only operator added to support compatibility with the operator of the same name in Java 7. It is used to indicate that generic types should be inferred from the declaration:

In dynamic Groovy, this is totally unused. In statically type checked Groovy, it is also optional since the Groovy type checker performs type inference whether this operator is present or not.

The call operator () is used to call a method named call implicitly. For any object which defines a call method, you can omit the .call part and use the call operator instead:

defines a method named . Note that it doesn’t need to implement
we can call the method using the classic method call syntax
or we can omit thanks to the call operator

The table below lists all groovy operators in order of precedence.

Level Operator(s) Name(s)

1

 

object creation, explicit parentheses

   

method call, closure, literal list/map

   

member access, method closure, field/attribute access

     

safe dereferencing, spread, spread-dot, spread-map

   

bitwise negate/pattern, not, typecast

     

list/map/array (safe) index, post inc/decrement

2

power

3

 

pre inc/decrement, unary plus, unary minus

4

   

multiply, div, remainder

5

 

addition, subtraction

6

           

left/right (unsigned) shift, inclusive/exclusive ranges

7

               

less/greater than/or equal, in, not in, instanceof, not instanceof, type coercion

8

       

equals, not equals, compare to, identical to, not identical to

 

regex find, regex match

9

binary/bitwise and

10

binary/bitwise xor

11

binary/bitwise or

12

logical and

13

logical or

14

ternary conditional

elvis operator

15

             
             

various assignments

Groovy allows you to overload the various operators so that they can be used with your own classes. Consider this simple class:

implements a special method called

Just by implementing the plus() method, the Bucket class can now be used with the + operator like so:

The two objects can be added together with the operator

All (non-comparator) Groovy operators have a corresponding method that you can implement in your own classes. The only requirements are that your method is public, has the correct name, and has the correct number of arguments. The argument types depend on what types you want to support on the right hand side of the operator. For example, you could support the statement

by implementing the plus() method with this signature:

Here is a complete list of the operators and their corresponding methods:

Operator Method Operator Method

a.plus(b)

a.getAt(b)

a.minus(b)

a.putAt(b, c)

a.multiply(b)

b.isCase(a)

a.div(b)

a.leftShift(b)

a.mod(b)

a.rightShift(b)

a.power(b)

a.rightShiftUnsigned(b)

a.or(b)

a.next()

a.and(b)

a.previous()

a.xor(b)

a.positive()

a.asType(b)

a.negative()

a.call()

a.bitwiseNegate()

1.3. Program structure

This chapter covers the program structure of the Groovy programming language.

Package names play exactly the same role as in Java. They allow us to separate the code base without any conflicts. Groovy classes must specify their package before the class definition, else the default package is assumed.

Defining a package is very similar to Java:

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 we’ll see below.

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

For example, Groovy provides several builder classes, such as MarkupBuilder . MarkupBuilder is inside the package groovy.xml so in order to use this class, you need to import it as shown:

Default imports are the imports that Groovy language provides by default. For example look at the following code:

The same code in Java needs an import statement to Date class like this: import java.util.Date. Groovy by default imports these classes for you.

The below imports are added by groovy for you:

This is done because the classes from these packages are most commonly used. By importing these boilerplate code is reduced.

A simple import is an import statement where you fully define the class name along with the package. For example the import statement import groovy.xml.MarkupBuilder in the code below is a simple import which directly refers to a class inside a package.

Groovy, like Java, provides a special way to import all classes from a package using * , the so-called star import. MarkupBuilder is a class which is in package groovy.xml , alongside another class called StreamingMarkupBuilder . In case you need to use both classes, you can do:

That’s perfectly valid code. But with a * import, we can achieve the same effect with just one line. The star imports all the classes under package groovy.xml :

One problem with * imports is that they can clutter your local namespace. But with the kinds of aliasing provided by Groovy, this can be solved easily.

Groovy’s static import capability allows you to reference imported classes as if they were static methods in your own class:

This is similar to Java’s static import capability but is a more dynamic than Java in that it allows you to define methods with the same name as an imported method as long as you have different types:

static import of method
declaration of method with same name as method statically imported above, but with a different parameter type
compile error in java, but is valid groovy code

If you have the same types, the imported class takes precedence.

Static imports with the as keyword provide an elegant solution to namespace problems. Suppose you want to get a Calendar instance, using its getInstance() method. It’s a static method, so we can use a static import. But instead of calling getInstance() every time, which can be misleading when separated from its class name, we can import it with an alias, to increase code readability:

Now, that’s clean!

A static star import is very similar to the regular star import. It will import all the static methods from the given class.

For example, lets say we need to calculate sines and cosines for our application. The class java.lang.Math has static methods named sin and cos which fit our need. With the help of a static star import, we can do:

As you can see, we were able to access the methods sin and cos directly, without the Math. prefix.

With type aliasing, we can refer to a fully qualified class name using a name of our choice. This can be done with the as keyword, as before.

For example we can import java.sql.Date as SQLDate and use it in the same file as java.util.Date without having to use the fully qualified name of either class:

1.3.3. Scripts versus classes

Groovy supports both scripts and classes. Take the following code for example:

define a class, the name is arbitrary
the method is usable as the main method of the class
the main body of the method

This is typical code that you would find coming from Java, where code has to be embedded into a class to be executable. Groovy makes it easier, the following code is equivalent:

A script can be considered as a class without needing to declare it, with some differences.

A groovy.lang.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. The previous example is therefore compiled as if it was the following:

The class extends the class
requires a method returning a value
the script body goes into the method
the method is automatically generated
and delegates the execution of the script on the method

If the script is in a file, then the base name of the file is used to determine the name of the generated script class. In this example, if the name of the file is Main.groovy , then the script class is going to be Main .

It is possible to define methods into a script, as illustrated here:

You can also mix methods and code. The generated script class will carry all methods into the script class, and assemble all script bodies into the run method:

script begins
a method is defined within the script body
and script continues

This code is internally converted into:

the method is copied as is into the generated script class
first statement is copied into the method
second statement is copied into the method
Even if Groovy creates a class from your script, it is totally transparent for the user. In particular, scripts are compiled to bytecode, and line numbers are preserved. This implies that if an exception is thrown in a script, the stack trace will show line numbers corresponding to the original script, not the generated code that we have shown.

Variables in a script do not require a type definition. This means that this script:

will behave the same as:

However, there is a semantic difference between the two:

if the variable is declared as in the first example, it is a local variable . It will be declared in the run method that the compiler will generate and will not be visible outside of the script main body. In particular, such a variable will not be visible in other methods of the script

if the variable is undeclared, it goes into the groovy.lang.Script#getBinding() . The binding is visible from the methods, and is especially important if you use a script to interact with an application and need to share data between the script and the application. Readers might refer to the integration guide for more information.

Another approach to making a variable visible to all methods, is to use the . A variable annotated this way will become a field of the generated script class and, as for local variables, access won’t involve the script . While not recommended, if you have a local variable or script field with the same name as a binding variable, you can use to access the binding variable.

1.4. Object orientation

This chapter covers the object-oriented aspects of the Groovy programming language.

1.4.1. Types

Groovy supports the same primitive types as defined by the Java Language Specification :

integral types: byte (8 bit), short (16 bit), int (32 bit) and long (64 bit)

floating-point types: float (32 bit) and double (64 bit)

the boolean type (one of true or false )

the char type (16 bit, usable as a numeric type, representing a UTF-16 code)

Also like Java, Groovy uses the respective wrapper classes when objects corresponding to any of the primitive types are required:

Table 4. primitive wrappers
Primitive type Wrapper class

boolean

Boolean

char

Character

short

Short

int

Integer

long

Long

float

Float

double

Double

Automatic boxing and unboxing occur when, for instance, calling a method requiring the wrapper class and passing it a primitive variable as the parameter, or vice-versa. This is similar to Java but Groovy takes the idea further.

In most scenarios, you can treat a primitive just like it was the full object wrapper equivalent. For instance, you can call .toString() or .equals(other) on a primitive. Groovy autowraps and unwraps between references and primitives as needed.

Here’s an example using int which is declared as a static field in a class (discussed shortly):

Primitive type is respected in the bytecode
Looking at the field at runtime shows it has been autowrapped

Now you may be concerned that this means every time you use a mathematical operator on a reference to a primitive that you’ll incur the cost of unboxing and reboxing the primitive. But this is not the case, as Groovy will compile your operators into their method equivalents and uses those instead. Additionally, Groovy will automatically unbox to a primitive when calling a Java method that takes a primitive parameter and automatically box primitive method return values from Java. However, be aware there are some differences from Java’s method resolution.

Apart from primitives, everything else is an object and has an associated class defining its type. We’ll discuss classes, and class-related or class-like things like interfaces, traits and records shortly.

We might declare two variables, of type String and List, as follows:

Groovy carries across the same concepts with regard to generics as Java. When defining classes and methods, it is possible to use a type parameter and create a generic class, interface, method or constructor.

Usage of generic classes and methods, regardless of whether they are defined in Java or Groovy, may involve supplying a type argument.

We might declare a variable, of type "list of string" , as follows:

Java employs type erasure for backwards compatibility with earlier versions of Java. Dynamic Groovy can be thought of as more aggressively applying type erasure. In general, less generics type information will be checked at compile time. Groovy’s static nature employs similar checks to Java with regard to generics information.

1.4.2. Classes

Groovy classes are very similar to Java classes, and are compatible with Java ones at JVM level. They may have methods, fields and properties (think JavaBeans properties but with less boilerplate). Classes and class members can have the same modifiers (public, protected, private, static, etc.) as in Java with some minor differences at the source level which are explained shortly.

The key differences between Groovy classes and their Java counterparts are:

Classes or methods with no visibility modifier are automatically public (a special annotation can be used to achieve package private visibility).

Fields with no visibility modifier are turned into properties automatically, which results in less verbose code, since explicit getter and setter methods aren’t needed. More on this aspect will be covered in the fields and properties section .

Classes do not need to have the same base name as their source file definitions but it is highly recommended in most scenarios (see also the next point about scripts).

One source file may contain one or more classes (but if a file contains any code not in a class, it is considered a script). Scripts are just classes with some special conventions and will have the same name as their source file (so don’t include a class definition within a script having the same name as the script source file).

The following code presents an example class.

class beginning, with the name
string field and property named
method definition

Normal classes refer to classes which are top level and concrete. This means they can be instantiated without restrictions from any other classes or scripts. This way, they can only be public (even though the public keyword may be suppressed). Classes are instantiated by calling their constructors, using the new keyword, as in the following snippet.

Inner class

Inner classes are defined within another classes. The enclosing class can use the inner class as usual. On the other side, an inner class can access members of its enclosing class, even if they are private. Classes other than the enclosing class are not allowed to access inner classes. Here is an example:

the inner class is instantiated and its method gets called
inner class definition, inside its enclosing class
even being private, a field of the enclosing class is accessed by the inner class

There are some reasons for using inner classes:

They increase encapsulation by hiding the inner class from other classes, which do not need to know about it. This also leads to cleaner packages and workspaces.

They provide a good organization, by grouping classes that are used by only one class.

They lead to more maintainable codes, since inner classes are near the classes that use them.

It is common for an inner class to be an implementation of some interface whose method(s) are needed by the outer class. The code below illustrates this typical usage pattern, here being used with threads.

Note that the class Inner2 is defined only to provide an implementation of the method run to class Outer2 . Anonymous inner classes help to eliminate verbosity in this case. That topic is covered shortly.

Groovy 3+ also supports Java syntax for non-static inner class instantiation, for example:

The earlier example of an inner class ( Inner2 ) can be simplified with an anonymous inner class. The same functionality can be achieved with the following code:

comparing with the last example of previous section, the was replaced by along with all its implementation
the method is invoked normally

Thus, there was no need to define a new class to be used just once.

Abstract classes represent generic concepts, thus, they cannot be instantiated, being created to be subclassed. Their members include fields/properties and abstract or concrete methods. Abstract methods do not have implementation, and must be implemented by concrete subclasses.

abstract classes must be declared with keyword
abstract methods must also be declared with keyword

Abstract classes are commonly compared to interfaces. There are at least two important differences of choosing one or another. First, while abstract classes may contain fields/properties and concrete methods, interfaces may contain only abstract methods (method signatures). Moreover, one class can implement several interfaces, whereas it can extend just one class, abstract or not.

Inheritance in Groovy resembles inheritance in Java. It provides a mechanism for a child class (or subclass) to reuse code or properties from a parent (or super class). Classes related through inheritance form an inheritance hierarchy. Common behavior and members are pushed up the hierarchy to reduce duplication. Specializations occur in child classes.

Different forms of inheritance are supported:

implementation inheritance where code (methods, fields or properties) from a superclass or from one or more traits is reused by a child class

contract inheritance where a class promises to provide particular abstract methods defined in a superclass , or defined in one or more traits or interfaces .

Parent classes share visible fields, properties or methods with child classes. A child class may have at most one parent class. The extends keyword is used immediately prior to giving the superclass type.

An interface defines a contract that a class needs to conform to. An interface only defines a list of methods that need to be implemented, but does not define the method’s implementation.

an interface needs to be declared using the keyword
an interface only defines method signatures

Methods of an interface are always public . It is an error to use protected or private methods in interfaces:

Using is a compile-time error

A class implements an interface if it defines the interface in its implements list or if any of its superclasses does:

The declares the interface using the keyword
Then implements the required method
Any instance of is also an instance of the interface

An interface can extend another interface:

the interface extends the interface using the keyword

It is worth noting that for a class to be an instance of an interface, it has to be explicit. For example, the following class defines the greet method as it is declared in the Greeter interface, but does not declare Greeter in its interfaces:

In other words, Groovy does not define structural typing. It is however possible to make an instance of an object implement an interface at runtime, using the as coercion operator:

create an instance of that does not implement the interface
coerce the instance into a at runtime
the coerced instance implements the interface

You can see that there are two distinct objects: one is the source object, a DefaultGreeter instance, which does not implement the interface. The other is an instance of Greeter that delegates to the coerced object.

Groovy interfaces do not support default implementation like Java 8 interfaces. If you are looking for something similar (but not equal), are close to interfaces, but allow default implementation as well as other important features described in this manual.

1.4.3. Class members

Constructors are special methods used to initialize an object with a specific state. As with normal methods, it is possible for a class to declare more than one constructor, so long as each constructor has a unique type signature. If an object doesn’t require any parameters during construction, it may use a no-arg constructor. If no constructors are supplied, an empty no-arg constructor will be provided by the Groovy compiler.

Groovy supports two invocation styles:

positional parameters are used in a similar to how you would use Java constructors

named parameters allow you to specify parameter names when invoking the constructor.

To create an object by using positional parameters, the respective class needs to declare one or more constructors. In the case of multiple constructors, each must have a unique type signature. The constructors can also be added to the class using the groovy.transform.TupleConstructor annotation.

Typically, once at least one constructor is declared, the class can only be instantiated by having one of its constructors called. It is worth noting that, in this case, you can’t normally create the class with named parameters. Groovy does support named parameters so long as the class contains a no-arg constructor or provides a constructor which takes a Map argument as the first (and potentially only) argument - see the next section for details.

There are three forms of using a declared constructor. The first one is the normal Java way, with the new keyword. The others rely on coercion of lists into the desired types. In this case, it is possible to coerce with the as keyword and by statically typing the variable.

Constructor declaration
Constructor invocation, classic Java way
Constructor usage, using coercion with keyword
Constructor usage, using coercion in assignment

If no (or a no-arg) constructor is declared, it is possible to create objects by passing parameters in the form of a map (property/value pairs). This can be in handy in cases where one wants to allow several combinations of parameters. Otherwise, by using traditional positional parameters it would be necessary to declare all possible constructors. Having a constructor where the first (and perhaps only) argument is a Map argument is also supported - such a constructor may also be added using the groovy.transform.MapConstructor annotation.

No constructor declared
No parameters given in the instantiation
parameter given in the instantiation
parameter given in the instantiation
and parameters given in the instantiation

It is important to highlight, however, that this approach gives more power to the constructor caller, while imposing an increased responsibility on the caller to get the names and value types correct. Thus, if greater control is desired, declaring constructors using positional parameters might be preferred.

While the example above supplied no constructor, you can also supply a no-arg constructor or a constructor where the first argument is a Map , most typically it’s the only argument.

When no (or a no-arg) constructor is declared, Groovy replaces the named constructor call by a call to the no-arg constructor followed by calls to the setter for each supplied named property.

When the first argument is a Map, Groovy combines all named parameters into a Map (regardless of ordering) and supplies the map as the first parameter. This can be a good approach if your properties are declared as final (since they will be set in the constructor rather than after the fact with setters).

You can support both named and positional construction by supply both positional constructors as well as a no-arg or Map constructor.

You can support hybrid construction by having a constructor where the first argument is a Map but there are also additional positional parameters. Use this style with caution.

Groovy methods are quite similar to other languages. Some peculiarities will be shown in the next subsections.

A method is defined with a return type or with the def keyword, to make the return type untyped. A method can also receive any number of arguments, which may not have their types explicitly declared. Java modifiers can be used normally, and if no visibility modifier is provided, the method is public.

Methods in Groovy always return some value. If no return statement is provided, the value evaluated in the last line executed will be returned. For instance, note that none of the following methods uses the return keyword.

Method with no return type declared and no parameter
Method with explicit return type and no parameter
Method with a parameter with no type defined
Static method with a String parameter

Like constructors, normal methods can also be called with named parameters. To support this notation, a convention is used where the first argument to the method is a Map . In the method body, the parameter values can be accessed as in normal maps ( map.key ). If the method has just a single Map argument, all supplied parameters must be named.

Named parameters can be mixed with positional parameters. The same convention applies, in this case, in addition to the Map argument as the first argument, the method in question will have additional positional arguments as needed. Supplied positional parameters when calling the method must be in order. The named parameters can be in any position. They are grouped into the map and supplied as the first parameter automatically.

Method call with additional argument of type
Method call with changed order of arguments

If we don’t have the Map as the first argument, then a Map must be supplied for that argument instead of named parameters. Failure to do so will lead to groovy.lang.MissingMethodException :

Method call throws , because the named argument parameter is not defined as the first argument

Above exception can be avoided if we replace named arguments with an explicit Map argument:

Explicit argument in place of named arguments makes invocation valid
Although Groovy allows you to mix named and positional parameters, it can lead to unnecessary confusion. Mix named and positional arguments with caution.

Default arguments make parameters optional. If the argument is not supplied, the method assumes a default value.

Parameters are dropped from the right, however mandatory parameters are never dropped.

The same rule applies to constructors as well as methods. If using @TupleConstructor , additional configuration options apply.

Groovy supports methods with a variable number of arguments. They are defined like this: def foo(p1, …​, pn, T…​ args) . Here foo supports n arguments by default, but also an unspecified number of further arguments exceeding n .

This example defines a method foo , that can take any number of arguments, including no arguments at all. args.length will return the number of arguments given. Groovy allows T[] as an alternative notation to T…​ . That means any method with an array as last parameter is seen by Groovy as a method that can take a variable number of arguments.

If a method with varargs is called with null as the vararg parameter, then the argument will be null and not an array of length one with null as the only element.

If a varargs method is called with an array as an argument, then the argument will be that array instead of an array of length one containing the given array as the only element.

Another important point are varargs in combination with method overloading. In case of method overloading Groovy will select the most specific method. For example if a method foo takes a varargs argument of type T and another method foo also takes one argument of type T , the second method is preferred.

Dynamic Groovy supports multiple dispatch (aka multimethods). When calling a method, the actual method invoked is determined dynamically based on the run-time type of methods arguments. First the method name and number of arguments will be considered (including allowance for varargs), and then the type of each argument. Consider the following method definitions:

Perhaps as expected, calling method with String and Integer parameters, invokes our third method definition.

Of more interest here is when the types are not known at compile time. Perhaps the arguments are declared to be of type Object (a list of such objects in our case). Java would determine that the method(Object, Object) variant would be selected in all cases (unless casts were used) but as can be seen in the following example, Groovy uses the runtime type and will invoke each of our methods once (and normally, no casting is needed):

For each of the first two of our three method invocations an exact match of argument types was found. For the third invocation, an exact match of method(Integer, Integer) wasn’t found but method(Object, Object) is still valid and will be selected.

Method selection then is about finding the closest fit from valid method candidates which have compatible parameter types. So, method(Object, Object) is also valid for the first two invocations but is not as close a match as the variants where types exactly match. To determine the closest fit, the runtime has a notion of the distance an actual argument type is away from the declared parameter type and tries to minimise the total distance across all parameters.

The following table illustrates some factors which affect the distance calculation.

Aspect Example

Directly implemented interfaces match more closely than ones from further up the inheritance hierarchy.

An Object array is preferred over an Object.

Non-vararg variants are favored over vararg variants.

If two vararg variants are applicable, the one which uses the minimum number of vararg arguments is preferred.

Interfaces are preferred over super classes.

For a primitive argument type, a declared parameter type which is the same or slightly larger is preferred.

In the case where two variants have exactly the same distance, this is deemed ambiguous and will cause a runtime exception:

Casting can be used to select the desired method:

Groovy automatically allows you to treat checked exceptions like unchecked exceptions. This means that you don’t need to declare any checked exceptions that a method may throw as shown in the following example which can throw a FileNotFoundException if the file isn’t found:

Nor will you be required to surround the call to the badRead method in the previous example within a try/catch block - though you are free to do so if you wish.

If you wish to declare any exceptions that your code might throw (checked or otherwise) you are free to do so. Adding exceptions won’t change how the code is used from any other Groovy code but can be seen as documentation for the human reader of your code. The exceptions will become part of the method declaration in the bytecode, so if your code might be called from Java, it might be useful to include them. Using an explicit checked exception declaration is illustrated in the following example:

Fields and Properties

A field is a member of a class, interface or trait which stores data. A field defined in a Groovy source file has:

a mandatory access modifier ( public , protected , or private )

one or more optional modifiers ( static , final , synchronized )

an optional type

a mandatory name

a field named , of type
a field named , of type
a field named of type

A field may be initialized directly at declaration:

the private field is initialized with

It is possible to omit the type declaration of a field. This is however considered a bad practice and in general it is a good idea to use strong typing for fields:

the field doesn’t declare a type
the field has a strong type

The difference between the two is important if you want to use optional type checking later. It is also important as a way to document the class design. However, in some cases like scripting or if you want to rely on duck typing it may be useful to omit the type.

A property is an externally visible feature of a class. Rather than just using a public field to represent such features (which provides a more limited abstraction and would restrict refactoring possibilities), the typical approach in Java is to follow the conventions outlined in the JavaBeans Specification , i.e. represent the property using a combination of a private backing field and getters/setters. Groovy follows these same conventions but provides a simpler way to define the property. You can define a property with:

an absent access modifier (no public , protected or private )

Groovy will then generate the getters/setters appropriately. For example:

creates a backing field, a and a method
creates a backing field, a and a method

If a property is declared final , no setter is generated:

defines a read-only property of type
defines a read-only property of type
assigns the parameter to the field
assigns the parameter to the field

Properties are accessed by name and will call the getter or setter transparently, unless the code is in the class which defines the property:

will directly access the field because the property is accessed from within the class that defines it
similarly a read access is done directly on the field
write access to the property is done outside of the class so it will implicitly call
read access to the property is done outside of the class so it will implicitly call
this will call the method on which performs a direct access to the field
this will call the method on which performs a direct read access to the field

It is worth noting that this behavior of accessing the backing field directly is done in order to prevent a stack overflow when using the property access syntax within a class that defines the property.

It is possible to list the properties of a class thanks to the meta properties field of an instance:

By convention, Groovy will recognize properties even if there is no backing field provided there are getters or setters that follow the Java Beans specification. For example:

writing is allowed because there is a pseudo-property
reading is allowed because there is a pseudo-readonly property
writing is allowed because there is a pseudo-write-only property

This syntactic sugar is at the core of many DSLs written in Groovy.

It is generally recommended that the first two letters of a property name are lowercase and for multi-word properties that camel case is used. In those cases, generated getters and setters will have a name formed by capitalizing the property name and adding a get or set prefix (or optionally "is" for a boolean getter). So, getLength would be a getter for a length property and setFirstName a setter for a firstName property. isEmpty might be the getter method name for a property named empty .

is allowed even though it isn’t following the recommended naming conventions. For this property, the accessor methods would be and . A consequence of this is that you aren’t allowed to have both a and a property, since they would have the same named accessor methods.

The JavaBeans specification makes a special case for properties which typically might be acronyms. If the first two letters of a property name are uppercase, no capitalization is performed (or more importantly, no decapitalization is done if generating the property name from the accessor method name). So, getURL would be the getter for a URL property.

recommend it, it does allow you to have what might seem like "duplicate named" properties, e.g. you can have and , or and . The getters would be and , and and respectively.

We have already seen that properties are defined by omitting the visibility modifier. In general, any other modifiers, e.g. transient would be copied across to the field. Two special cases are worth noting:

final , which we saw earlier is for read-only properties, is copied onto the backing field but also causes no setter to be defined

static is copied onto the backing field but also causes the accessor methods to be static

If you wish to have a modifier like final also carried over to the accessor methods, you can write your properties long hand or consider using a split property definition .

Annotations, including those associated with AST transforms, are copied on to the backing field for the property. This allows AST transforms which are applicable to fields to be applied to properties, e.g.:

Confirms no eager initialization
Normal property access
Confirms initialization upon property access

Groovy’s property syntax is a convenient shorthand when your class design follows certain conventions which align with common JavaBean practice. If your class doesn’t exactly fit these conventions, you can certainly write the getter, setter and backing field long hand like you would in Java. However, Groovy does provide a split definition capability which still provides a shortened syntax while allowing slight adjustments to the conventions. For a split definition, you write a field and a property with the same name and type. Only one of the field or property may have an initial value.

For split properties, annotations on the field remain on the backing field for the property. Annotations on the property part of the definition are copied onto the getter and setter methods.

This mechanism allows a number of common variations that property users may wish to use if the standard property definition doesn’t exactly fit their needs. For example, if the backing field should be protected rather than private :

Protected backing field for name property instead of normal private one
Declare name property

Or, the same example but with a package-private backing field:

Declare name property
Package-private backing field for name property instead of normal private one

As a final example, we may wish to apply method-related AST transforms, or in general, any annotation to the setters/getters, e.g. to have the accessors be synchronized:

Backing field for name property
Declare name property with annotation for setter/getter

The automatic generation of accessor methods doesn’t occur if there is an explicit definition of the getter or setter in the class. This allows you to modify the normal behavior of such a getter or setter if needed. Inherited accessor methods aren’t normally considered but if an inherited accessor method is marked final, that will also cause no generation of an additional accessor method to honor the final requirement of no subclassing of such methods.

1.4.4. Annotations

Annotation definition.

An annotation is a kind of special interface dedicated at annotating elements of the code. An annotation is a type which superinterface is the java.lang.annotation.Annotation interface. Annotations are declared in a very similar way to interfaces, using the @interface keyword:

An annotation may define members in the form of methods without bodies and an optional default value. The possible member types are limited to:

primitive types

java.lang.String

java.lang.Class

an java.lang.Enum

another java.lang.annotation.Annotation

or any array of the above

For example:

an annotation defining a member of type
an annotation defining a member of type with a default value of
an annotation defining a member of type the primitive type
an annotation defining a member of type
an annotation defining a member which type is an array of another annotation type
an annotation defining a member which type is the enumeration type

Unlike in the Java language, 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.

An annotation can be applied on various elements of the code:

applies to the method
applies to the class
applies to the variable

In order to limit the scope where an annotation can be applied, it is necessary to declare it on the annotation definition, using the java.lang.annotation.Target annotation. For example, here is how you would declare that an annotation can be applied to a class or a method:

the annotation is meant to annotate an annotation with a scope.
will therefore only be allowed on or

The list of possible targets is available in the java.lang.annotation.ElementType .

Groovy does not support the and element types which were introduced in Java 8.

When an annotation is used, it is required to set at least all members that do not have a default value. For example:

However it is possible to omit value= in the declaration of the value of an annotation if the member value is the only one being set:

we can omit the because it has a default value, but needs to be set
since is the only mandatory member without a default, we can omit
if both and need to be set, it is required to use for the default member

The visibility of an annotation depends on its retention policy. The retention policy of an annotation is set using the java.lang.annotation.Retention annotation:

the annotation annotates the annotation
so will have a retention

The list of possible retention targets and description is available in the java.lang.annotation.RetentionPolicy enumeration. The choice usually depends on whether you want an annotation to be visible at compile time or runtime.

An interesting feature of annotations in Groovy is that you can use a closure as an annotation value. Therefore annotations may be used with a wide variety of expressions and still have IDE support. For example, imagine a framework where you want to execute some methods based on environmental constraints like the JDK version or the OS. One could write the following code:

For the @OnlyIf annotation to accept a Closure as an argument, you only have to declare the value as a Class :

To complete the example, let’s write a sample runner that would use that information:

create a new instance of the class passed as an argument (the task class)
emulate an environment which is JDK 6 and not Windows
iterate on all declared methods of the task class
if the method is public and takes no-argument
try to find the annotation
if it is found get the and create a new out of it
set the of the closure to our environment variable
call the closure, which is the annotation closure. It will return a
if it is , call the method
if the method is not annotated with , execute the method anyway
after that, return the task object

Then the runner can be used this way:

Meta-annotations

Meta-annotations, also known as annotation aliases are annotations that are replaced at compile time by other annotations (one meta-annotation is an alias for one or more annotations). Meta-annotations can be used to reduce the size of code involving multiple annotations.

Let’s start with a simple example. Imagine you have the  @Service and  @Transactional annotations and that you want to annotate a class with both:

Given the multiplication of annotations that you could add to the same class, a meta-annotation could help by reducing the two annotations with a single one having the very same semantics. For example, we might want to write this instead:

is a meta-annotation

A meta-annotation is declared as a regular annotation but annotated with @AnnotationCollector and the list of annotations it is collecting. In our case, the @TransactionalService annotation can be written:

annotate the meta-annotation with
annotate the meta-annotation with
annotate the meta-annotation with

Groovy supports both precompiled and source form meta-annotations. This means that your meta-annotation  may be precompiled, or you can have it in the same source tree as the one you are currently compiling.

INFO: Meta-annotations are a Groovy-only feature. There is no chance for you to annotate a Java class with a meta-annotation and hope it will do the same as in Groovy. Likewise, you cannot write a meta-annotation in Java: both the meta-annotation definition  and usage have to be Groovy code. But you can happily collect Java annotations and Groovy annotations within your meta-annotation.

When the Groovy compiler encounters a class annotated with a meta-annotation, it  replaces it with the collected annotations. So, in our previous example, it will replace  @TransactionalService with  @Transactional and  @Service :

The conversion from a meta-annotation to the collected annotations is performed during the semantic analysis compilation phase. 

In addition to replacing the alias with the collected annotations, a meta-annotation is capable of processing them, including arguments.

Meta-annotations can collect annotations which have parameters. To illustrate this, we will imagine two annotations, each of them accepting one argument:

And suppose that you want to create a meta-annotation named  @Explosive :

By default, when the annotations are replaced, they will get the annotation parameter values as they were defined in the alias . More interesting, the meta-annotation supports overriding specific values:

the value provided as a parameter to  overrides the one defined in the annotation

If two annotations define the same parameter name, the default processor will copy the annotation value to all annotations that accept this parameter:

the annotation defines the member of type
the annotation also defines the member of type
the meta-annotation aggregates and
class is annotated with and
the value of the annotation on is
while the value of the annotation on is
class is annotated with
then the value of the annotation on is
and the value of the annotation on is also

In the second case, the meta-annotation value was copied in both @Foo and @Bar annotations.

It is a compile time error if the collected annotations define the same members with incompatible types. For example if on the previous example defined a value of type but defined a value of type .

It is however possible to customize the behavior of meta-annotations and describe how collected annotations are expanded. We’ll look at how to do that shortly but first there is an advanced processing option to cover.

The @AnnotationCollector annotation supports a mode parameter which can be used to alter how the default processor handles annotation replacement in the presence of duplicate annotations.

INFO: Custom processors (discussed next) may or may not support this parameter.

As an example, suppose you create a meta-annotation containing the @ToString annotation and then place your meta-annotation on a class that already has an explicit @ToString annotation. Should this be an error? Should both annotations be applied? Does one take priority over the other? There is no correct answer. In some scenarios it might be quite appropriate for any of these answers to be correct. So, rather than trying to preempt one correct way to handle the duplicate annotation issue, Groovy lets you write your own custom meta-annotation processors (covered next) and lets you write whatever checking logic you like within AST transforms - which are a frequent target for aggregating. Having said that, by simply setting the mode , a number of commonly expected scenarios are handled automatically for you within any extra coding. The behavior of the mode parameter is determined by the AnnotationCollectorMode enum value chosen and is summarized in the following table.

Mode

Description

DUPLICATE

Annotations from the annotation collection will always be inserted. After all transforms have been run, it will be an error if multiple annotations (excluding those with SOURCE retention) exist.

PREFER_COLLECTOR

Annotations from the collector will be added and any existing annotations with the same name will be removed.

PREFER_COLLECTOR_MERGED

Annotations from the collector will be added and any existing annotations with the same name will be removed but any new parameters found within existing annotations will be merged into the added annotation.

PREFER_EXPLICIT

Annotations from the collector will be ignored if any existing annotations with the same name are found.

PREFER_EXPLICIT_MERGED

Annotations from the collector will be ignored if any existing annotations with the same name are found but any new parameters on the collector annotation will be added to existing annotations.

A custom annotation processor will let you choose how to expand a meta-annotation into collected annotations. The behaviour of the meta-annotation is, in this case, totally up to you. To do this, you must:

create a meta-annotation processor, extending org.codehaus.groovy.transform.AnnotationCollectorTransform

declare the processor to be used in the meta-annotation declaration

To illustrate this, we are going to explore how the meta-annotation @CompileDynamic is implemented.

@CompileDynamic is a meta-annotation that expands itself to  @CompileStatic(TypeCheckingMode.SKIP) . The problem is that the default meta annotation processor doesn’t support enums and the annotation value TypeCheckingMode.SKIP is one.

The naive implementation here would not work:

Instead, we will define it like this:

The first thing you may notice is that our interface is no longer annotated with  @CompileStatic . The reason for this is that we rely on the processor parameter instead, that references a class which will  generate the annotation.

Here is how the custom processor is implemented:

our custom processor is written in Groovy, and for better compilation performance, we use static compilation
the custom processor has to extend
create a class node representing the annotation type
create a class node representing the enum type
is the node found in the meta-annotation. Usually unused.
is the meta-annotation being expanded, here it is
is the node being annotated with the meta-annotation
is the being compiled
we create a new annotation node for
we create an expression equivalent to
we add that expression to the annotation node, which is now
return the generated annotation

In the example, the visit method is the only method which has to be overridden. It is meant to return a list of annotation nodes that will be added to the node annotated with the meta-annotation. In this example, we return a single one corresponding to @CompileStatic(TypeCheckingMode.SKIP) .

1.4.5. Traits

Traits are a structural construct of the language which allows:

composition of behaviors

runtime implementation of interfaces

behavior overriding

compatibility with static type checking/compilation

They can be seen as interfaces carrying both default implementations and state . A trait is defined using the trait keyword:

declaration of a trait
declaration of a method inside a trait

Then it can be used like a normal interface using the implements keyword:

Adds the trait to the class capabilities
instantiate a new
the class automatically gets the behavior of the trait

Traits allow a wide range of capabilities, from simple composition to testing, which are described thoroughly in this section.

Declaring a method in a trait can be done like any regular method in a class:

In addition, traits may declare abstract methods too, which therefore need to be implemented in the class implementing the trait:

implementing class will have to declare the method
can be mixed with a concrete method

Then the trait can be used like this:

implement the trait
since was abstract, it is required to implement it
then can be called

Traits may also define private methods. Those methods will not appear in the trait contract interface:

define a private method in the trait
the public message calls by default
create a class implementing the trait
can be called
but not
Traits only support and methods. Neither nor scopes are supported.

If we have a class implementing a trait, conceptually implementations from the trait methods are "inherited" into the class. But, in reality, there is no base class containing such implementations. Rather, they are woven directly into the class. A final modifier on a method just indicates what the modifier will be for the woven method. While it would likely be considered bad style to inherit and override or multiply inherit methods with the same signature but a mix of final and non-final variants, Groovy doesn’t prohibit this scenario. Normal method selection applies and the modifier used will be determined from the resulting method. You might consider creating a base class which implements the desired trait(s) if you want trait implementation methods that can’t be overridden.

this represents the implementing instance. Think of a trait as a superclass. This means that when you write:

then calling:

will return the same instance:

Traits may implement interfaces, in which case the interfaces are declared using the implements keyword:

declaration of a normal interface
add to the list of implemented interfaces
declare a class that implements the trait
implement the missing method
the implementation comes from the trait
make sure implements the interface
make sure implements the trait

A trait may define properties, like in the following example:

declare a property inside a trait
declare a class which implements the trait
the property is automatically made visible
it can be accessed using the regular property accessor
or using the regular getter syntax

Since traits allow the use of private methods, it can also be interesting to use private fields to store state. Traits will let you do that:

declare a private field inside a trait
declare a public method that increments the counter and returns it
declare a class that implements the trait
the method can use the private field to keep state
This is a major difference with . While virtual extension methods do not carry state, traits can. Moreover, traits in Groovy are supported starting with Java 6, because their implementation does not rely on virtual extension methods. This means that even if a trait can be seen from a Java class as a regular interface, that interface will have default methods, only abstract ones.

Public fields work the same way as private fields, but in order to avoid the diamond problem , field names are remapped in the implementing class:

declare a public inside the trait
declare a class implementing the trait
create an instance of that class
the public field is available, but renamed

The name of the field depends on the fully qualified name of the trait. All dots ( . ) in package are replaced with an underscore ( _ ), and the final name includes a double underscore. So if the type of the field is String , the name of the package is my.package , the name of the trait is Foo and the name of the field is bar , in the implementing class, the public field will appear as:

While traits support public fields, it is not recommended to use them and considered as a bad practice.

Traits can be used to implement multiple inheritance in a controlled way. For example, we can have the following traits:

And a class implementing both traits:

the class implements both and
creates a new instance of
we can call the method from
but also the method from

Traits encourage the reuse of capabilities among objects, and the creation of new classes by the composition of existing behavior.

Traits provide default implementations for methods, but it is possible to override them in the implementing class. For example, we can slightly change the example above, by having a duck which quacks:

define a method specific to , named
override the default implementation of so that we use instead
the duck is still flying, from the default implementation
comes from the class
no longer uses the default implementation from

Extending traits

Traits may extend another trait, in which case you must use the extends keyword:

the trait defines a single property
the trait the trait
adds a new method which has access to the property of the super-trait
the property is visible from the class implementing
as is the method

Alternatively, a trait may extend multiple traits. In that case, all super traits must be declared in the implements clause:

trait defines the property
trait defines the property
is a trait which inherits both and

Duck typing and traits

Traits can call any dynamic code, like a normal Groovy class. This means that you can, in the body of a method, call methods which are supposed to exist in an implementing class, without having to explicitly declare them in an interface. This means that traits are fully compatible with duck typing:

the expects the method to be defined
the class does implement the method using
calling the method triggers a call to which is handled by

It is also possible for a trait to implement MOP methods like methodMissing or propertyMissing , in which case implementing classes will inherit the behavior from the trait, like in this example:

create a trait implementing several MOP methods
the class defines a property
the class defines a method
calling an existing property will call the method from
calling a non-existing property will call the method from the trait
will call defined on the trait
will call defined on the trait
calling an existing method on
but calling a non-existing method thanks to the trait

Multiple inheritance conflicts

It is possible for a class to implement multiple traits. If some trait defines a method with the same signature as a method in another trait, we have a conflict:

trait defines a method named returning a
trait defines the very same method
class implements both traits

In this case, the default behavior is that the method from the last declared trait in the implements clause wins. Here, B is declared after A so the method from B will be picked up:

In case this behavior is not the one you want, you can explicitly choose which method to call using the Trait.super.foo syntax. In the example above, we can ensure the method from trait A is invoked by writing this:

explicit call of from the trait
calls the version from instead of using the default resolution, which would be the one from

Runtime implementation of traits

Groovy also supports implementing traits dynamically at runtime. It allows you to "decorate" an existing object using a trait. As an example, let’s start with this trait and the following class:

the trait defines an method
the class does implement the trait
only defines a method

Then if we do:

the call to extra would fail because Something is not implementing Extra . It is possible to do it at runtime with the following syntax:

use of the keyword to coerce an object to a trait
then can be called on the object
and is still callable
When coercing an object to a trait, the result of the operation is not the same instance. It is guaranteed that the coerced object will implement both the trait the interfaces that the original object implements, but the result will be an instance of the original class.

Should you need to implement several traits at once, you can use the withTraits method instead of the as keyword:

call to will fail because doesn’t implement
call to will fail because doesn’t implement
will wrap into something which implements and
will now pass because implements
will now pass because also implements
When coercing an object to multiple traits, the result of the operation is not the same instance. It is guaranteed that the coerced object will implement both the traits the interfaces that the original object implements, but the result will be an instance of the original class.

Chaining behavior

Groovy supports the concept of stackable traits . The idea is to delegate from one trait to the other if the current trait is not capable of handling a message. To illustrate this, let’s imagine a message handler interface like this:

Then you can compose a message handler by applying small behaviors. For example, let’s define a default handler in the form of a trait:

Then any class can inherit the behavior of the default handler by implementing the trait:

Now what if you want to log all messages, in addition to the default handler? One option is to write this:

explicitly implement the method
perform logging
continue by delegating to the trait

This works but this approach has drawbacks:

the logging logic is bound to a "concrete" handler

we have an explicit reference to DefaultHandler in the on method, meaning that if we happen to change the trait that our class implements, code will be broken

As an alternative, we can write another trait which responsibility is limited to logging:

the logging handler is itself a handler
prints the message it receives
then makes it delegate the call to the next trait in the chain

Then our class can be rewritten as this:

which will print:

As the priority rules imply that LoggerHandler wins because it is declared last, then a call to on will use the implementation from LoggingHandler . But the latter has a call to super , which means the next trait in the chain. Here, the next trait is DefaultHandler so both will be called:

The interest of this approach becomes more evident if we add a third handler, which is responsible for handling messages that start with say :

a handler specific precondition
if the precondition is not met, pass the message to the next handler in the chain

Then our final handler looks like this:

Which means:

messages will first go through the logging handler

the logging handler calls super which will delegate to the next handler, which is the SayHandler

if the message starts with say , then the handler consumes the message

if not, the say handler delegates to the next handler in the chain

This approach is very powerful because it allows you to write handlers that do not know each other and yet let you combine them in the order you want. For example, if we execute the code, it will print:

but if we move the logging handler to be the second one in the chain, the output is different:

The reason is that now, since the SayHandler consumes the message without calling super , the logging handler is not called anymore.

If a class implements multiple traits and a call to an unqualified super is found, then:

if the class implements another trait, the call delegates to the next trait in the chain

if there isn’t any trait left in the chain, super refers to the super class of the implementing class ( this )

For example, it is possible to decorate final classes thanks to this behavior:

define a trait named , supposed to be applied on a at runtime
redefine the method
remove all 'o’s from the string
then delegate to
in case is called, delegate to
runtime implementation of the trait on a instance
the string which has been appended no longer contains the letter

In this example, when super.append is encountered, there is no other trait implemented by the target object, so the method which is called is the original append method, that is to say the one from StringBuilder . The same trick is used for toString , so that the string representation of the proxy object which is generated delegates to the toString of the StringBuilder instance.

Advanced features

If a trait defines a single abstract method, it is candidate for SAM (Single Abstract Method) type coercion. For example, imagine the following trait:

the method is not abstract and calls the abstract method
is an abstract method

Since getName is the single abstract method in the Greeter trait, you can write:

the closure "becomes" the implementation of the single abstract method
the greet method accepts the SAM type Greeter as parameter
we can call it directly with a closure

In Java 8, interfaces can have default implementations of methods. If a class implements an interface and does not provide an implementation for a default method, then the implementation from the interface is chosen. Traits behave the same but with a major difference: the implementation from the trait is always used if the class declares the trait in its interface list and that it doesn’t provide an implementation even if a super class does.

This feature can be used to compose behaviors in a very precise way, in case you want to override the behavior of an already implemented method.

To illustrate the concept, let’s start with this simple example:

In this example, we create a simple test case which uses two properties ( config and shell ) and uses those in multiple test methods. Now imagine that you want to test the same, but with another distinct compiler configuration. One option is to create a subclass of SomeTest :

It works, but what if you have actually multiple test classes, and that you want to test the new configuration for all those test classes? Then you would have to create a distinct subclass for each test class:

Then what you see is that the setup method of both tests is the same. The idea, then, is to create a trait:

Then use it in the subclasses:

It would allow us to dramatically reduce the boilerplate code, and reduces the risk of forgetting to change the setup code in case we decide to change it. Even if setup is already implemented in the super class, since the test class declares the trait in its interface list, the behavior will be borrowed from the trait implementation!

This feature is in particular useful when you don’t have access to the super class source code. It can be used to mock methods or force a particular implementation of a method in a subclass. It lets you refactor your code to keep the overridden logic in a single trait and inherit a new behavior just by implementing it. The alternative, of course, is to override the method in every place you would have used the new code.

It’s worth noting that if you use runtime traits, the methods from the trait are preferred to those of the proxied object:
the class defines a property which results in a method
is a trait which defines as returning
the default object will return
coerces into at runtime
returns because is taken from the
Again, don’t forget that dynamic trait coercion returns a distinct object which only implements the original interfaces, as well as the traits.

There are several conceptual differences with mixins, as they are available in Groovy. Note that we are talking about runtime mixins, not the @Mixin annotation which is deprecated in favour of traits.

First of all, methods defined in a trait are visible in bytecode:

internally, the trait is represented as an interface (without default or static methods) and several helper classes

this means that an object implementing a trait effectively implements an interface

those methods are visible from Java

they are compatible with type checking and static compilation

Methods added through a mixin are, on the contrary, only visible at runtime:

class defines
class defines
mixin B into A
we can call
we can also call
the object is an instance of
but it’s an instanceof

The last point is actually a very important and illustrates a place where mixins have an advantage over traits: the instances are not modified, so if you mixin some class into another, there isn’t a third class generated, and methods which respond to A will continue responding to A even if mixed in.

The following instructions are subject to caution. Static member support is work in progress and still experimental. The information below is valid for 4.0.21 only.

It is possible to define static methods in a trait, but it comes with numerous limitations:

Traits with static methods cannot be compiled statically or type checked. All static methods, properties and field are accessed dynamically (it’s a limitation from the JVM).

Static methods do not appear within the generated interfaces for each trait.

The trait is interpreted as a template for the implementing class, which means that each implementing class will get its own static methods, properties and fields. So a static member declared on a trait doesn’t belong to the Trait , but to its implementing class.

You should typically not mix static and instance methods of the same signature. The normal rules for applying traits apply (including multiple inheritance conflict resolution). If the method chosen is static but some implemented trait has an instance variant, a compilation error will occur. If the method chosen is the instance variant, the static variant will be ignored (the behavior is similar to static methods in Java interfaces for this case).

Let’s start with a simple example:

the static field is declared in the trait
a static method is also declared in the trait
the static field is updated the trait
a static method is made available to the implementing class
the static field is to avoid the diamond issue

As usual, it is not recommended to use public fields. Anyway, should you want this, you must understand that the following code would fail:

because there is no static field CALLED defined on the trait itself. Likewise, if you have two distinct implementing classes, each one gets a distinct static field:

class implements the trait
class also implements the trait
is only called on
the static field on is updated
but the static field on is not, because it is

We have seen that traits are stateful. It is possible for a trait to define fields or properties, but when a class implements a trait, it gets those fields/properties on a per-trait basis. So consider the following example:

The trait defines two properties, x and y , as well as a sum method. Now let’s create a class which implements the trait:

The result of calling f is 3 , because f delegates to sum in the trait, which has state. But what if we write this instead?

Override property
Override property
Call from trait

If you call elem.f() , what is the expected output? Actually it is:

The reason is that the sum method accesses the fields of the trait. So it is using the x and y values defined in the trait. If you want to use the values from the implementing class, then you need to dereference fields by using getters and setters, like in this last example:

Sometimes you will want to write a trait that can only be applied to some type. For example, you may want to apply a trait on a class that extends another class which is beyond your control, and still be able to call those methods. To illustrate this, let’s start with this example:

A class, beyond your control (in a library, …​) defines a method
A class, beyond your control (in a library, …​)
Defines a communicating trait for devices that can call the service
Defines as a communicating device
The method from the trait is called, and is resolved

It is clear, here, that the Communicating trait can only apply to Device . However, there’s no explicit contract to indicate that, because traits cannot extend classes. However, the code compiles and runs perfectly fine, because id in the trait method will be resolved dynamically. The problem is that there is nothing that prevents the trait from being applied to any class which is not a Device . Any class which has an id would work, while any class that does not have an id property would cause a runtime error.

The problem is even more complex if you want to enable type checking or apply @CompileStatic on the trait: because the trait knows nothing about itself being a Device , the type checker will complain saying that it does not find the id property.

One possibility is to explicitly add a getId method in the trait, but it would not solve all issues. What if a method requires this as a parameter, and actually requires it to be a Device ?

If you want to be able to call this in the trait, then you will explicitly need to cast this into a Device . This can quickly become unreadable with explicit casts to this everywhere.

In order to make this contract explicit, and to make the type checker aware of the type of itself , Groovy provides a @SelfType annotation that will:

let you declare the types that a class that implements this trait must inherit or implement

throw a compile-time error if those type constraints are not satisfied

So in our previous example, we can fix the trait using the @groovy.transform.SelfType annotation:

Now if you try to implement this trait on a class that is not a device, a compile-time error will occur:

The error will be:

In conclusion, self types are a powerful way of declaring constraints on traits without having to declare the contract directly in the trait or having to use casts everywhere, maintaining separation of concerns as tight as it should be.

Both @Sealed and @SelfType restrict classes which use a trait but in orthogonal ways. Consider the following example:

All usages of the trait must implement or extend both and
Only or can use the trait

For the degenerate case where a single class implements a trait, e.g.:

Then, either:

Or just if and are in the same source file

could express this constraint. Generally, the former of these is preferred.

Limitations

Traits are not officially compatible with AST transformations. Some of them, like will be applied on the trait itself (not on implementing classes), while others will apply on both the implementing class and the trait. There is absolutely no guarantee that an AST transformation will run on a trait as it does on a regular class, so use it at your own risk!

Within traits, prefix and postfix operations are not allowed if they update a field of the trait:

is defined within the trait, postfix increment is not allowed
is defined within the trait, prefix decrement is not allowed

A workaround is to use the += operator instead.

1.4.6. Record classes (incubating)

Record classes, or records for short, are a special kind of class useful for modelling plain data aggregates. They provide a compact syntax with less ceremony than normal classes. Groovy already has AST transforms such as @Immutable and @Canonical which already dramatically reduce ceremony but records have been introduced in Java and record classes in Groovy are designed to align with Java record classes.

For example, suppose we want to create a Message record representing an email message. For the purposes of this example, let’s simplify such a message to contain just a from email address, a to email address, and a message body . We can define such a record as follows:

We’d use the record class in the same way as a normal class, as shown below:

The reduced ceremony saves us from defining explicit fields, getters and toString , equals and hashCode methods. In fact, it’s a shorthand for the following rough equivalent:

Note the special naming convention for record getters. They are the same name as the field (rather than the often common JavaBean convention of capitalized with a "get" prefix). Rather than referring to a record’s fields or properties, the term component is typically used for records. So our Message record has from , to , and body components.

Like in Java, you can override the normally implicitly supplied methods by writing your own:

You can also use generics with records in the normal way. For example, consider the following Coord record definition:

It can be used as follows:

Special record features

Records have an implicit constructor. This can be overridden in the normal way by providing your own constructor - you need to make sure you set all the fields if you do this. However, for succinctness, a compact constructor syntax can be used where the parameter declaration part of a normal constructor is elided. For this special case, the normal implicit constructor is still provided but is augmented by the supplied statements in the compact constructor definition:

Groovy native records follow the special conventions for serializability which apply to Java records. Groovy record-like classes (discussed below) follow normal Java class serializability conventions.

Groovy enhancements

Groovy supports default values for constructor arguments. This capability is also available for records as shown in the following record definition which has default values for y and color :

Arguments when left off (dropping one or more arguments from the right) are replaced with their defaults values as shown in the following example:

This processing follows normal Groovy conventions for default arguments for constructors, essentially automatically providing the constructors with the following signatures:

Named arguments may also be used (default values also apply here):

You can disable default argument processing as shown here:

This will produce a single constructor as per the default with Java. It will be an error if you drop off arguments in this scenario.

You can force all properties to have a default value as shown here:

Any property/field without an explicit initial value will be given the default value for the argument’s type (null, or zero/false for primitives).

We previously described a Message record and displayed it’s rough equivalent. Groovy in fact steps through an intermediate stage where the record keyword is replaced by the class keyword and an accompanying @RecordType annotation:

Then @RecordType itself is processed as a meta-annotation (annotation collector) and expanded into its constituent sub-annotations such as @TupleConstructor , @POJO , @RecordBase , and others. This is in some sense an implementation detail which can often be ignored. However, if you wish to customise or configure the record implementation, you may wish to drop back to the @RecordType style or augment your record class with one of the constituent sub-annotations.

As per Java, you can customize a record’s toString method by writing your own. If you prefer a more declarative style, you can alternatively use Groovy’s @ToString transform to override the default record toString . As an example, you can a three-dimensional point record as follows:

We customise the toString by including the package name (excluded by default for records) and by caching the toString value since it won’t change for this immutable record. We are also ignoring null values (the default value for z in our definition).

We can have a similar definition for a two-dimensional point:

We can see here that without the package name it would have the same toString as our previous example.

We can obtain the component values from a record as a list like so:

You can use @RecordOptions(toList=false) to disable this feature.

We can obtain the component values from a record as a map like so:

You can use @RecordOptions(toMap=false) to disable this feature.

We can obtain the number of components in a record like so:

You can use @RecordOptions(size=false) to disable this feature.

We can use Groovy’s normal positional indexing to obtain a particular component in a record like so:

You can use @RecordOptions(getAt=false) to disable this feature.

Optional Groovy features

It can be useful to make a copy of a record with some components changed. This can be done using an optional copyWith method which takes named arguments. Record components are set from the supplied arguments. For components not mentioned, a (shallow) copy of the original record component is used. Here is how you might use copyWith for the Fruit record:

The copyWith functionality can be disabled by setting the RecordOptions#copyWith annotation attribute to false .

As with Java, records by default offer shallow immutability. Groovy’s @Immutable transform performs defensive copying for a range of mutable data types. Records can make use of this defensive copying to gain deep immutability as follows:

These examples illustrate the principal behind Groovy’s record feature offering three levels of convenience:

Using the record keyword for maximum succinctness

Supporting low-ceremony customization using declarative annotations

Allowing normal method implementations when full control is required

You can obtain the components of a record as a typed tuple:

Groovy has a limited number of TupleN classes. If you have a large number of components in your record, you might not be able to use this feature.

Groovy supports creating record-like classes as well as native records. Record-like classes don’t extend Java’s Record class and such classes won’t be seen by Java as records but will otherwise have similar properties.

The @RecordOptions annotation (part of @RecordType ) supports a mode annotation attribute which can take one of three values (with AUTO being the default):

Produces a class similar to what Java would do. Produces an error when compiling on JDKs earlier than JDK16.

Produces a record-like class for all JDK versions.

Produces a native record for JDK16+ and emulates the record otherwise.

Whether you use the record keyword or the @RecordType annotation is independent of the mode.

1.4.7. Sealed hierarchies (incubating)

Sealed classes, interfaces and traits restrict which subclasses can extend/implement them. Prior to sealed classes, class hierarchy designers had two main options:

Make a class final to allow no extension.

Make the class public and non-final to allow extension by anyone.

Sealed classes provide a middle-ground compared to these all or nothing choices.

Sealed classes are also more flexible than other tricks previously used to try to achieve a middle-ground. For example, for class hierarchies, access modifiers like protected and package-private give some ability to restrict inheritance hierarchies but often at the expense of flexible use of those hierarchies.

Sealed hierarchies provide full inheritance within a known hierarchy of classes, interfaces and traits but disable or only provide controlled inheritance outside the hierarchy.

As an example, suppose we want to create a shape hierarchy containing only circles and squares. We also want a shape interface to be able to refer to instances in our hierarchy. We can create the hierarchy as follows:

Groovy also supports an alternative annotation syntax. We think the keyword style is nicer but you might choose the annotation style if your editor doesn’t yet have Groovy 4 support.

We can have a reference of type ShapeI which, thanks to the permits clause, can point to either a Circle or Square and, since our classes are final , we know no additional classes will be added to our hierarchy in the future. At least not without changing the permits clause and recompiling.

In general, we might want to have some parts of our class hierarchy immediately locked down like we have here, where we marked the subclasses as final but other times we might want to allow further controlled inheritance.

  In this example, our permitted subclasses for Shape are Circle , Polygon , and Rectangle . Circle is final and hence that part of the hierarchy cannot be extended. Polygon is implicitly non-sealed and RegularPolygon is explicitly marked as non-sealed . That means our hierarchy is open to any further extension by subclassing, as seen with Polygon → RegularPolygon and RegularPolygon → Hexagon . Rectangle is itself sealed which means that part of the hierarchy can be extended but only in a controlled way (only Square is permitted).

Sealed classes are useful for creating enum-like related classes which need to contain instance specific data. For instance, we might have the following enum:

but we now wish to also add weather specific instance data to weather forecasts. We can alter our abstraction as follows:

Sealed hierarchies are also useful when specifying Algebraic or Abstract Data Types (ADTs) as shown in the following example:

Sealed hierarchies work well with records as shown in the following example:

Java provides no default modifier for subclasses of sealed classes and requires that one of final , sealed or non-sealed be specified. Groovy defaults to non-sealed but you can still use non-sealed/@NonSealed if you wish. We anticipate the style checking tool CodeNarc will eventually have a rule that looks for the presence of non-sealed so developers wanting that stricter style will be able to use CodeNarc and that rule if they want.

Currently, Groovy doesn’t check that all classes mentioned in permittedSubclasses are available at compile-time and compiled along with the base sealed class. This may change in a future version of Groovy.

Groovy supports annotating classes as sealed as well as "native" sealed classes.

The @SealedOptions annotation supports a mode annotation attribute which can take one of three values (with AUTO being the default):

Produces a class similar to what Java would do. Produces an error when compiling on JDKs earlier than JDK17.

Indicates the class is sealed using the @Sealed annotation. This mechanism works with the Groovy compiler for JDK8+ but is not recognised by the Java compiler.

Produces a native record for JDK17+ and emulates the record otherwise.

Whether you use the sealed keyword or the @Sealed annotation is independent of the mode.

1.5. Closures

This chapter covers Groovy Closures. A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its surrounding scope. In opposition to the formal definition of a closure, Closure in the Groovy language can also contain free variables which are defined outside of its surrounding scope. While breaking the formal concept of a closure, it offers a variety of advantages which are described in this chapter.

1.5.1. Syntax

A closure definition follows this syntax:

Where [closureParameters->] is an optional comma-delimited list of parameters, and statements are 0 or more Groovy statements. The parameters look similar to a method parameter list, and these parameters may be typed or untyped.

When a parameter list is specified, the -> character is required and serves to separate the arguments from the closure body. The statements portion consists of 0, 1, or many Groovy statements.

Some examples of valid closure definitions:

A closure referencing a variable named
It is possible to explicitly separate closure parameters from code by adding an arrow ( )
A closure using an implicit parameter ( )
An alternative version where is an explicit parameter
In that case it is often better to use an explicit name for the parameter
A closure accepting two typed parameters
A closure can contain multiple statements

A closure is an instance of the groovy.lang.Closure class, making it assignable to a variable or a field as any other variable, despite being a block of code:

You can assign a closure to a variable, and it is an instance of
If not using or , use as the type
Optionally, you can specify the return type of the closure by using the generic type of

A closure, as an anonymous block of code, can be called like any other method. If you define a closure which takes no argument like this:

Then the code inside the closure will only be executed when you call the closure, which can be done by using the variable as if it was a regular method:

Alternatively, you can be explicit and use the call method:

The principle is the same if the closure accepts arguments:

define a closure which accepts an as a parameter
it can be called directly
or using the method
same goes for a closure with an implicit argument ( )
which can be called directly using
or using

Unlike a method, a closure always returns a value when called. The next section discusses how to declare closure arguments, when to use them and what is the implicit "it" parameter .

1.5.2. Parameters

Parameters of closures follow the same principle as parameters of regular methods:

an optional default value

Parameters are separated with commas:

When a closure does not explicitly define a parameter list (using -> ), a closure always defines an implicit parameter, named it . This means that this code:

is strictly equivalent to this one:

If you want to declare a closure which accepts no argument and must be restricted to calls without arguments, then you must declare it with an explicit empty argument list:

It is possible for a closure to declare variable arguments like any other method. Vargs methods are methods that can accept a variable number of arguments if the last parameter is of variable length (or an array) like in the next examples:

A closure accepting a variable number of strings as first parameter
It may be called using any number of arguments having to explicitly wrap them into an array
The same behavior is directly available if the parameter is declared as an array
As long as the parameter is an array or an explicit vargs type

1.5.3. Delegation strategy

Groovy defines closures as instances of the Closure class . It makes it very different from lambda expressions in Java 8 . Delegation is a key concept in Groovy closures which has no equivalent in lambdas. The ability to change the delegate or change the delegation strategy of closures make it possible to design beautiful domain specific languages (DSLs) in Groovy.

Owner, delegate and this

To understand the concept of delegate, we must first explain the meaning of this inside a closure. A closure actually defines 3 distinct things:

this corresponds to the enclosing class where the closure is defined

owner corresponds to the enclosing object where the closure is defined, which may be either a class or a closure

delegate corresponds to a third party object where methods calls or properties are resolved whenever the receiver of the message is not defined

In a closure, calling getThisObject will return the enclosing class where the closure is defined. It is equivalent to using an explicit this :

a closure is defined inside the class, and returns
calling the closure will return the instance of where the closure is defined
in general, you will just want to use the shortcut notation
and it returns the same object
if the closure is defined in an inner class
in the closure return the inner class, not the top-level one
in case of nested closures, like here being defined inside the scope of
then corresponds to the closest outer class, not the enclosing closure!

It is of course possible to call methods from the enclosing class this way:

the closure calls on , which will actually call the method on the enclosing object, that is to say the instance

The owner of a closure is very similar to the definition of this in a closure with a subtle difference: it will return the direct enclosing object, be it a closure or a class:

a closure is defined inside the class, and returns
calling the closure will return the instance of where the closure is defined
in general, you will just want to use the shortcut notation
and it returns the same object
if the closure is defined in an inner class
in the closure return the inner class, not the top-level one
but in case of nested closures, like here being defined inside the scope of
then corresponds to the enclosing closure, hence a different object from !

The delegate of a closure can be accessed by using the delegate property or calling the getDelegate method. It is a powerful concept for building domain specific languages in Groovy. While this and owner refer to the lexical scope of a closure, the delegate is a user defined object that a closure will use. By default, the delegate is set to owner :

you can get the delegate of a closure calling the method
or using the property
both return the same object
which is the enclosing class or closure
in particular in case of nested closures
will correspond to the

The delegate of a closure can be changed to any object . Let’s illustrate this by creating two classes which are not subclasses of each other but both define a property called name :

Then let’s define a closure which fetches the name property on the delegate:

Then by changing the delegate of the closure, you can see that the target object will change:

At this point, the behavior is not different from having a target variable defined in the lexical scope of the closure:

However, there are major differences:

in the last example, target is a local variable referenced from within the closure

the delegate can be used transparently, that is to say without prefixing method calls with delegate. as explained in the next paragraph.

Whenever, in a closure, a property is accessed without explicitly setting a receiver object, then a delegation strategy is involved:

is not referencing a variable in the lexical scope of the closure
we can change the delegate of the closure to be an instance of
and the method call will succeed

The reason this code works is that the name property will be resolved transparently on the delegate object! This is a very powerful way to resolve properties or method calls inside closures. There’s no need to set an explicit delegate. receiver: the call will be made because the default delegation strategy of the closure makes it so. A closure actually defines multiple resolution strategies that you can choose:

Closure.OWNER_FIRST is the default strategy . If a property/method exists on the owner , then it will be called on the owner. If not, then the delegate is used.

Closure.DELEGATE_FIRST reverses the logic: the delegate is used first, then the owner

Closure.OWNER_ONLY will only resolve the property/method lookup on the owner: the delegate will be ignored.

Closure.DELEGATE_ONLY will only resolve the property/method lookup on the delegate: the owner will be ignored.

Closure.TO_SELF can be used by developers who need advanced meta-programming techniques and wish to implement a custom resolution strategy: the resolution will not be made on the owner or the delegate but only on the closure class itself. It makes only sense to use this if you implement your own subclass of Closure .

Let’s illustrate the default "owner first" strategy with this code:

for the illustration, we define a closure member which references "name"
both the and the class define a property
Using the default strategy, the property is resolved on the owner first
so if we change the to which is an instance of
there is no change in the result: is first resolved on the of the closure

However, it is possible to change the resolution strategy of the closure:

By changing the resolveStrategy , we are modifying the way Groovy will resolve the "implicit this" references: in this case, name will first be looked in the delegate, then if not found, on the owner. Since name is defined in the delegate, an instance of Thing , then this value is used.

The difference between "delegate first" and "delegate only" or "owner first" and "owner only" can be illustrated if one of the delegate (resp. owner) does not have such a method or property:

for "owner first" it doesn’t matter what the delegate is
for "delegate only" having as the delegate succeeds
for "delegate only" having as the delegate fails

In this example, we define two classes which both have a name property but only the Person class declares an age . The Person class also declares a closure which references age . We can change the default resolution strategy from "owner first" to "delegate only". Since the owner of the closure is the Person class, then we can check that if the delegate is an instance of Person , calling the closure is successful, but if we call it with a delegate being an instance of Thing , it fails with a groovy.lang.MissingPropertyException . Despite the closure being defined inside the Person class, the owner is not used.

A comprehensive explanation about how to use this feature to develop DSLs can be found in a .

When describing the "owner first" delegation strategy we spoke about using a property/method from the owner if it " existed " otherwise using the respective property/method from the delegate. And a similar story for "delegate first" but in reverse. Instead of using the word " existed ", it would have been more accurate to use the wording " handled ". That means that for "owner first", if the property/method exists in the owner, or it has a propertyMissing/methodMissing hook, then the owner will handle the member access.

We can see this in action with a slightly altered version of our previous example:

In this example, even though our instance of the Thing class (our delegate for the last use of cl ) has no age property, the fact that it handles the missing property via its propertyMissing hook, means that age will be -1 .

Take the following code:

The code behaves as you would expect, but what happens if you add:

You will see that the assert fails! There are two reasons for this:

a GString only evaluates lazily the toString representation of values

the syntax ${x} in a GString does not represent a closure but an expression to $x , evaluated when the GString is created.

In our example, the GString is created with an expression referencing x . When the GString is created, the value of x is 1, so the GString is created with a value of 1. When the assert is triggered, the GString is evaluated and 1 is converted to a String using toString . When we change x to 2, we did change the value of x , but it is a different object, and the GString still references the old one.

A will only change its representation if the values it references are mutating. If the references change, nothing will happen.

If you need a real closure in a GString and for example enforce lazy evaluation of variables, you need to use the alternate syntax ${→ x} like in the fixed example:

And let’s illustrate how it differs from mutation with this code:

the class has a method returning the property
we create a first named
we create another named
the variable is set to
and a closure is created, referencing the value of , that is to say
so when we evaluate the string, it returns
if we change to
the string still evaluates to because it was the of when the was created
so if we mutate to change the name to
this time the is correctly mutated

So if you don’t want to rely on mutating objects or wrapping objects, you must use closures in GString by explicitly declaring an empty argument list:

Closures can be converted into interfaces or single-abstract method types. Please refer to this section of the manual for a complete description.

1.5.6. Functional programming

Closures, like lambda expressions in Java 8 are at the core of the functional programming paradigm in Groovy. Some functional programming operations on functions are available directly on the Closure class, like illustrated in this section.

In Groovy, currying refers to the concept of partial application. It does not correspond to the real concept of currying in functional programming because of the different scoping rules that Groovy applies on closures. Currying in Groovy will let you set the value of one parameter of a closure, and it will return a new closure accepting one less argument.

Left currying is the fact of setting the left-most parameter of a closure, like in this example:

the closure defines two parameters
will set the first parameter to , creating a new closure (function) which accepts a single
so the new function call be called with only a
and it is equivalent to calling with two parameters

Similarly to left currying, it is possible to set the right-most parameter of a closure:

the closure defines two parameters
will set the last parameter to , creating a new closure (function) which accepts a single
so the new function call be called with only an
and it is equivalent to calling with two parameters

In case a closure accepts more than 2 parameters, it is possible to set an arbitrary parameter using ncurry :

the function defines 3 parameters
will set the second parameter (index = 1) to , creating a new volume function which accepts length and height
that function is equivalent to calling omitting the width
it is also possible to set multiple parameters, starting from the specified index
the resulting function accepts as many parameters as the initial one minus the number of parameters set by

Memoization allows the result of the call of a closure to be cached. It is interesting if the computation done by a function (closure) is slow, but you know that this function is going to be called often with the same arguments. A typical example is the Fibonacci suite. A naive implementation may look like this:

It is a naive implementation because 'fib' is often called recursively with the same arguments, leading to an exponential algorithm:

computing fib(15) requires the result of fib(14) and fib(13)

computing fib(14) requires the result of fib(13) and fib(12)

Since calls are recursive, you can already see that we will compute the same values again and again, although they could be cached. This naive implementation can be "fixed" by caching the result of calls using memoize :

The cache works . This means that you should be very careful if you use memoization with something else than primitive or boxed primitive types.

The behavior of the cache can be tweaked using alternate methods:

memoizeAtMost will generate a new closure which caches at most n values

memoizeAtLeast will generate a new closure which caches at least n values

memoizeBetween will generate a new closure which caches at least n values and at most n values

The cache used in all memoize variants is an LRU cache.

Closure composition corresponds to the concept of function composition, that is to say creating a new function by composing two or more functions (chaining calls), as illustrated in this example:

Recursive algorithms are often restricted by a physical limit: the maximum stack height. For example, if you call a method that recursively calls itself too deep, you will eventually receive a StackOverflowException .

An approach that helps in those situations is by using Closure and its trampoline capability.

Closures are wrapped in a TrampolineClosure . Upon calling, a trampolined Closure will call the original Closure waiting for its result. If the outcome of the call is another instance of a TrampolineClosure , created perhaps as a result to a call to the trampoline() method, the Closure will again be invoked. This repetitive invocation of returned trampolined Closures instances will continue until a value other than a trampolined Closure is returned. That value will become the final result of the trampoline. That way, calls are made serially, rather than filling the stack.

Here’s an example of the use of trampoline() to implement the factorial function:

It is often practical to be able to use a regular method as a closure. For example, you might want to use the currying abilities of a closure, but those are not available to normal methods. In Groovy, you can obtain a closure from any method with the method pointer operator .

1.6. Semantics

This chapter covers the semantics of the Groovy programming language.

1.6.1. Statements

Variables can be defined using either their type (like String ) or by using the keyword def (or var ) followed by a variable name:

def and var act as a type placeholder, i.e. a replacement for the type name, when you do not want to give an explicit type. It could be that you don’t care about the type at compile time or are relying on type inference (with Groovy’s static nature). It is mandatory for variable definitions to have a type or placeholder. If left out, the type name will be deemed to refer to an existing variable (presumably declared earlier). For scripts, undeclared variables are assumed to come from the Script binding. In other cases, you will get a missing property (dynamic Groovy) or compile time error (static Groovy). If you think of def and var as an alias of Object , you will understand in an instant.

Variable definitions can provide an initial value, in which case it’s like having a declaration and assignment (which we cover next) all in one.

Variable definition types can be refined by using generics, like in . To learn more about the generics support, please read the .

Variable assignment

You can assign values to variables for later use. Try the following:

Groovy supports multiple assignment, i.e. where multiple variables can be assigned at once, e.g.:

You can provide types as part of the declaration if you wish:

As well as used when declaring variables it also applies to existing variables:

The syntax works for arrays as well as lists, as well as methods that return either of these:

If the left hand side has too many variables, excess ones are filled with null’s:

If the right hand side has too many variables, the extra ones are ignored:

In the section describing Groovy’s operators, the case of the subscript operator has been covered, explaining how you can override the getAt() / putAt() method.

With this technique, we can combine multiple assignments and the subscript operator methods to implement object destructuring .

Consider the following immutable Coordinates class, containing a pair of longitude and latitude doubles, and notice our implementation of the getAt() method:

Now let’s instantiate this class and destructure its longitude and latitude:

we create an instance of the class
then, we use a multiple assignment to get the individual longitude and latitude values
and we can finally assert their values.

Control structures

Conditional structures.

Groovy supports the usual if - else syntax from Java

Groovy also supports the normal Java "nested" if then else if syntax:

The switch statement in Groovy is backwards compatible with Java code; so you can fall through cases sharing the same code for multiple matches.

One difference though is that the Groovy switch statement can handle any kind of switch value and different kinds of matching can be performed.

Switch supports the following kinds of comparisons:

Class case values match if the switch value is an instance of the class

Regular expression case values match if the toString() representation of the switch value matches the regex

Collection case values match if the switch value is contained in the collection. This also includes ranges (since they are Lists)

Closure case values match if the calling the closure returns a result which is true according to the Groovy truth

If none of the above are used then the case value matches if the case value equals the switch value

When using a closure case value, the default parameter is actually the switch value (in our example, variable ).

Groovy also supports switch expressions as shown in the following example:

Looping structures

Groovy supports the standard Java / C for loop:

The more elaborate form of Java’s classic for loop with comma-separate expressions is now supported. Example:

Groovy has supported multi-assignment statements since Groovy 1.6:

These can now appear in for loops:

The for loop in Groovy is much simpler and works with any kind of array, collection, Map, etc.

Groovy also supports the Java colon variation with colons:

Groovy supports the usual while {…​} loops like Java:

Java’s class do/while loop is now supported. Example:

Exception handling is the same as Java.

You can specify a complete try-catch-finally , a try-catch , or a try-finally set of blocks.

Braces are required around each block’s body.

We can put code within a 'finally' clause following a matching 'try' clause, so that regardless of whether the code in the 'try' clause throws an exception, the code in the finally clause will always execute:

With the multi catch block (since Groovy 2.0), we’re able to define several exceptions to be catch and treated by the same catch block:

Groovy often provides better alternatives to Java 7’s try -with-resources statement for Automatic Resource Management (ARM). That syntax is now supported for Java programmers migrating to Groovy and still wanting to use the old style:

Which yields the following output:

Unlike Java with which Groovy shares the assert keyword, the latter in Groovy behaves very differently. First of all, an assertion in Groovy is always executed, independently of the -ea flag of the JVM. It makes this a first class choice for unit tests. The notion of "power asserts" is directly related to how the Groovy assert behaves.

A power assertion is decomposed into 3 parts:

The result of the assertion is very different from what you would get in Java. If the assertion is true, then nothing happens. If the assertion is false, then it provides a visual representation of the value of each sub-expressions of the expression being asserted. For example:

Will yield:

Power asserts become very interesting when the expressions are more complex, like in the next example:

Which will print the value for each sub-expression:

In case you don’t want a pretty printed error message like above, you can fall back to a custom error message by changing the optional message part of the assertion, like in this example:

Which will print the following error message:

Any statement can be associated with a label. Labels do not impact the semantics of the code and can be used to make the code easier to read like in the following example:

Despite not changing the semantics of the labelled statement, it is possible to use labels in the break instruction as a target for jump, as in the next example. However, even if this is allowed, this coding style is in general considered a bad practice:

It is important to understand that by default labels have no impact on the semantics of the code, however they belong to the abstract syntax tree (AST) so it is possible for an AST transformation to use that information to perform transformations over the code, hence leading to different semantics. This is in particular what the Spock Framework does to make testing easier.

1.6.2. Expressions

Expressions are the building blocks of Groovy programs that are used to reference existing values and execute code to create new ones.

Groovy supports many of the same kinds of expressions as Java, including:

Table 5. Expressions like Java

, ,

, ,

,

expressions

,

expressions

expressions

Groovy also has some of its own special expressions:

Table 6. Special expressions

Groovy also expands on the normal dot-notation used in Java for member access. Groovy provides special support for accessing hierarchical data structures by specifying the path in the hierarchy of some data of interest. These Groovy path expressions are known as GPath expressions.

GPath expressions

GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be identified. In this sense, it has similar aims and scope as XPath does for XML. GPath is often used in the context of processing XML, but it really applies to any object graph. Where XPath uses a filesystem-like path notation, a tree hierarchy with parts separated by a slash / , GPath use a dot-object notation to perform object navigation.

As an example, you can specify a path to an object or element of interest:

a.b.c → for XML, yields all the c elements inside b inside a

a.b.c → for POJOs, yields the c properties for all the b properties of a (sort of like a.getB().getC() in JavaBeans)

In both cases, the GPath expression can be viewed as a query on an object graph. For POJOs, the object graph is most often built by the program being written through object instantiation and composition; for XML processing, the object graph is the result of parsing the XML text, most often with classes like XmlParser or XmlSlurper. See Processing XML for more in-depth details on consuming XML in Groovy.

notation:

→ map-like notation : the href attribute of all the a elements

→ property notation : an alternative way of expressing this

→ direct notation : yet another alternative way of expressing this

Let’s see an example of a GPath expression on a simple object graph , the one obtained using java reflection. Suppose you are in a non-static method of a class having another method named aMethodFoo

the following GPath expression will get the name of that method:

More precisely , the above GPath expression produces a list of String, each being the name of an existing method on this where that name ends with Foo .

Now, given the following methods also defined in that class:

then the following GPath expression will get the names of (1) and (3) , but not (2) or (0) :

We can decompose the expression this.class.methods.name.grep(~/.*Bar/) to get an idea of how a GPath is evaluated:

property accessor, equivalent to this.getClass() in Java, yields a Class object.

property accessor, equivalent to this.getClass().getMethods() , yields an array of Method objects.

apply a property accessor on each element of an array and produce a list of the results.

call method grep on each element of the list yielded by this.class.methods.name and produce a list of the results.

A sub-expression like yields an array because this is what calling in Java would produce. expressions do not have a convention where a means a list or anything like that.

One powerful feature of GPath expression is that property access on a collection is converted to a property access on each element of the collection with the results collected into a collection. Therefore, the expression this.class.methods.name could be expressed as follows in Java:

Array access notation can also be used in a GPath expression where a collection is present :

array access are zero-based in GPath expressions

Here is an example with an XML document and various form of GPath expressions:

There is one node under
There are two nodes under
There is one element having an attribute with value
Text value of element of first element of second element under is 'anotherKey'

Further details about GPath expressions for XML are in the XML User Guide .

1.6.3. Promotion and coercion

The rules of number promotion are specified in the section on math operations .

Closure to type coercion

A SAM type is a type which defines a single abstract method. This includes:

Any closure can be converted into a SAM type using the as operator:

However, the as Type expression is optional since Groovy 2.2.0. You can omit it and simply write:

which means you are also allowed to use method pointers, as shown in the following example:

The second and probably more important use case for closure to SAM type coercion is calling a method which accepts a SAM type. Imagine the following method:

Then you can call it with a closure, without having to create an explicit implementation of the interface:

But since Groovy 2.2.0, you are also able to omit the explicit coercion and call the method as if it used a closure:

As you can see, this has the advantage of letting you use the closure syntax for method calls, that is to say put the closure outside the parenthesis, improving the readability of your code.

In addition to SAM types, a closure can be coerced to any type and in particular interfaces. Let’s define the following interface:

You can coerce a closure into the interface using the as keyword:

This produces a class for which all methods are implemented using the closure:

But it is also possible to coerce a closure to any class. For example, we can replace the interface that we defined with class without changing the assertions:

Usually using a single closure to implement an interface or a class with multiple methods is not the way to go. As an alternative, Groovy allows you to coerce a map into an interface or a class. In that case, keys of the map are interpreted as method names, while the values are the method implementation. The following example illustrates the coercion of a map into an Iterator :

Of course this is a rather contrived example, but illustrates the concept. You only need to implement those methods that are actually called, but if a method is called that doesn’t exist in the map a MissingMethodException or an UnsupportedOperationException is thrown, depending on the arguments passed to the call, as in the following example:

The type of the exception depends on the call itself:

MissingMethodException if the arguments of the call do not match those from the interface/class

UnsupportedOperationException if the arguments of the call match one of the overloaded methods of the interface/class

Groovy allows transparent String (or GString ) to enum values coercion. Imagine you define the following enum:

then you can assign a string to the enum without having to use an explicit as coercion:

It is also possible to use a GString as the value:

However, this would throw a runtime error ( IllegalArgumentException ):

Note that it is also possible to use implicit coercion in switch statements:

in particular, see how the case use string constants. But if you call a method that uses an enum with a String argument, you still have to use an explicit as coercion:

It is possible for a class to define custom coercion strategies by implementing the asType method. Custom coercion is invoked using the as operator and is never implicit. As an example, imagine you defined two classes, Polar and Cartesian , like in the following example:

And that you want to convert from polar coordinates to cartesian coordinates. One way of doing this is to define the asType method in the Polar class:

which allows you to use the as coercion operator:

Putting it all together, the Polar class looks like this:

but it is also possible to define asType outside of the Polar class, which can be practical if you want to define custom coercion strategies for "closed" classes or classes for which you don’t own the source code, for example using a metaclass:

Using the as keyword is only possible if you have a static reference to a class, like in the following code:

But what if you get the class by reflection, for example by calling Class.forName ?

Trying to use the reference to the class with the as keyword would fail:

It is failing because the as keyword only works with class literals. Instead, you need to call the asType method:

1.6.4. Optionality

Method calls can omit the parentheses if there is at least one parameter and there is no ambiguity:

Parentheses are required for method calls without parameters or ambiguous method calls:

In Groovy semicolons at the end of the line can be omitted, if the line contains only a single statement.

This means that:

can be more idiomatically written as:

Multiple statements in a line require semicolons to separate them:

In Groovy, the last expression evaluated in the body of a method or a closure is returned. This means that the return keyword is optional.

Can be shortened to:

By default, Groovy classes and methods are public . Therefore this class:

is identical to this class:

1.6.5. The Groovy Truth

Groovy decides whether an expression is true or false by applying the rules given below.

True if the corresponding 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.

In order to customize whether groovy evaluates your object to true or false implement the asBoolean() method:

Groovy will call this method to coerce your object to a boolean value, e.g.:

1.6.6. Typing

Optional typing is the idea that a program can work even if you don’t put an explicit type on a variable. Being a dynamic language, Groovy naturally implements that feature, for example when you declare a variable:

is declared using an explicit type,
we can call the method on a

Groovy will let you write this instead:

is declared using
we can still call the method, because the type of is resolved at runtime

So it doesn’t matter that you use an explicit type here. It is in particular interesting when you combine this feature with static type checking , because the type checker performs type inference.

Likewise, Groovy doesn’t make it mandatory to declare the types of a parameter in a method:

can be rewritten using def as both return type and parameter types, in order to take advantage of duck typing, as illustrated in this example:

both the return type and the parameter types use
it makes it possible to use the method with
but also with since the method is defined
Using the keyword here is recommended to describe the intent of a method which is supposed to work on any type, but technically, we could use instead and the result would be the same: is, in Groovy, strictly equivalent to using .

Eventually, the type can be removed altogether from both the return type and the descriptor. But if you want to remove it from the return type, you then need to add an explicit modifier for the method, so that the compiler can make a difference between a method declaration and a method call, like illustrated in this example:

if we want to omit the return type, an explicit modifier has to be set.
it is still possible to use the method with
and also with
Omitting types is in general considered a bad practice in method parameters or method return types for public APIs. While using in a local variable is not really a problem because the visibility of the variable is limited to the method itself, while set on a method parameter, will be converted to in the method signature, making it difficult for users to know which is the expected type of the arguments. This means that you should limit this to cases where you are explicitly relying on duck typing.

Static type checking

By default, Groovy performs minimal type checking at compile time. Since it is primarily a dynamic language, most checks that a static compiler would normally do aren’t possible at compile time. A method added via runtime metaprogramming might alter a class or object’s runtime behavior. Let’s illustrate why in the following example:

the class only defines two properties, and
we can create an instance of Person
and call a method named

It is quite common in dynamic languages for code such as the above example not to throw any error. How can this be? In Java, this would typically fail at compile time. However, in Groovy, it will not fail at compile time, and if coded correctly, will also not fail at runtime. In fact, to make this work at runtime, one possibility is to rely on runtime metaprogramming. So just adding this line after the declaration of the Person class is enough:

This means that in general, in Groovy, you can’t make any assumption about the type of an object beyond its declaration type, and even if you know it, you can’t determine at compile time what method will be called, or which property will be retrieved. It has a lot of interest, going from writing DSLs to testing, which is discussed in other sections of this manual.

However, if your program doesn’t rely on dynamic features and that you come from the static world (in particular, from a Java mindset), not catching such "errors" at compile time can be surprising. As we have seen in the previous example, the compiler cannot be sure this is an error. To make it aware that it is, you have to explicitly instruct the compiler that you are switching to a type checked mode. This can be done by annotating a class or a method with @groovy.transform.TypeChecked .

When type checking is activated, the compiler performs much more work:

type inference is activated, meaning that even if you use def on a local variable for example, the type checker will be able to infer the type of the variable from the assignments

method calls are resolved at compile time, meaning that if a method is not declared on a class, the compiler will throw an error

in general, all the compile time errors that you are used to find in a static language will appear: method not found, property not found, incompatible types for method calls, number precision errors, …​

In this section, we will describe the behavior of the type checker in various situations and explain the limits of using @TypeChecked on your code.

The @TypeChecked annotation

The groovy.transform.TypeChecked annotation enables type checking. It can be placed on a class:

Or on a method:

In the first case, all methods, properties, fields, inner classes, …​ of the annotated class will be type checked, whereas in the second case, only the method and potential closures or anonymous inner classes that it contains will be type checked.

The scope of type checking can be restricted. For example, if a class is type checked, you can instruct the type checker to skip a method by annotating it with @TypeChecked(TypeCheckingMode.SKIP) :

the class is marked as type checked
so the method is automatically type checked
but is marked with
the type checker doesn’t complain about missing properties here

In the previous example, SentenceBuilder relies on dynamic code. There’s no real Hello method or property, so the type checker would normally complain and compilation would fail. Since the method that uses the builder is marked with TypeCheckingMode.SKIP , type checking is skipped for this method, so the code will compile, even if the rest of the class is type checked.

The following sections describe the semantics of type checking in Groovy.

An object o of type A can be assigned to a variable of type T if and only if:

or T is one of String , boolean , Boolean or Class

or o is null and T is not a primitive type

or T is an array and A is an array and the component type of A is assignable to the component type of T

or T is an array and A is a collection or stream and the component type of A is assignable to the component type of T

or T is a superclass of A

or T is an interface implemented by A

or T or A are a primitive type and their boxed types are assignable

or T extends groovy.lang.Closure and A is a SAM-type (single abstract method type)

or T and A derive from java.lang.Number and conform to the following table

Table 7. Number types (java.lang.XXX)
T A Examples

Double

Any but BigDecimal or BigInteger

Float

Any type but BigDecimal, BigInteger or Double

Long

Any type but BigDecimal, BigInteger, Double or Float

Integer

Any type but BigDecimal, BigInteger, Double, Float or Long

Short

Any type but BigDecimal, BigInteger, Double, Float, Long or Integer

Byte

Byte

In addition to the assignment rules above, if an assignment is deemed invalid, in type checked mode, a list literal or a map literal A can be assigned to a variable of type T if:

the assignment is a variable declaration and A is a list literal and T has a constructor whose parameters match the types of the elements in the list literal

the assignment is a variable declaration and A is a map literal and T has a no-arg constructor and a property for each of the map keys

For example, instead of writing:

You can use a "list constructor":

or a "map constructor":

If you use a map constructor, additional checks are done on the keys of the map to check if a property of the same name is defined. For example, the following will fail at compile time:

The type checker will throw an error at compile time

In type checked mode, methods are resolved at compile time. Resolution works by name and arguments. The return type is irrelevant to method selection. Types of arguments are matched against the types of the parameters following those rules:

An argument o of type A can be used for a parameter of type T if and only if:

or T is a String and A is a GString

or T and A derive from java.lang.Number and conform to the same rules as assignment of numbers

If a method with the appropriate name and arguments is not found at compile time, an error is thrown. The difference with "normal" Groovy is illustrated in the following example:

is an error, but since we’re in a dynamic mode, the error is not caught at compile time

The example above shows a class that Groovy will be able to compile. However, if you try to create an instance of MyService and call the doSomething method, then it will fail at runtime , because printLine doesn’t exist. Of course, we already showed how Groovy could make this a perfectly valid call, for example by catching MethodMissingException or implementing a custom metaclass, but if you know you’re not in such a case, @TypeChecked comes handy:

is this time a compile-time error

Just adding @TypeChecked will trigger compile time method resolution. The type checker will try to find a method printLine accepting a String on the MyService class, but cannot find one. It will fail compilation with the following message:

Cannot find matching method MyService#printLine(java.lang.String)

It is important to understand the logic behind the type checker: it is a compile-time check, so by definition, the type checker is not aware of any kind of metaprogramming that you do. This means that code which is perfectly valid without will compile anymore if you activate type checking. This is in particular true if you think of duck typing:
we define a class which defines a method
we define another class which also defines a method
is loosely typed, so since the method is , we will obtain a compile-time error
even if in non type-checked Groovy, this would have passed

There are possible workarounds, like introducing an interface, but basically, by activating type checking, you gain type safety but you loose some features of the language. Hopefully, Groovy introduces some features like flow typing to reduce the gap between type-checked and non type-checked Groovy.

Type inference

When code is annotated with @TypeChecked , the compiler performs type inference. It doesn’t simply rely on static types, but also uses various techniques to infer the types of variables, return types, literals, …​ so that the code remains as clean as possible even if you activate the type checker.

The simplest example is inferring the type of a variable:

a variable is declared using the keyword
calling is allowed by the type checker
calling will fail at compile time

The reason the call to toUpperCase works is because the type of message was inferred as being a String .

It is worth noting that although the compiler performs type inference on local variables, it does not perform any kind of type inference on fields, always falling back to the declared type of a field. To illustrate this, let’s take a look at this example:

uses as a declaration type
uses as a declaration type
we can assign to
yet calling fails at compile time because the field is not typed properly
we can assign a to a field of type
and this time is allowed
if we assign a to a local variable
then calling is allowed on the local variable

Why such a difference? The reason is thread safety . At compile time, we can’t make any guarantee about the type of a field. Any thread can access any field at any time and between the moment a field is assigned a variable of some type in a method and the time is used the line after, another thread may have changed the contents of the field. This is not the case for local variables: we know if they "escape" or not, so we can make sure that the type of a variable is constant (or not) over time. Note that even if a field is final, the JVM makes no guarantee about it, so the type checker doesn’t behave differently if a field is final or not.

This is one of the reasons why we recommend to use fields. While using for local variables is perfectly fine thanks to type inference, this is not the case for fields, which also belong to the public API of a class, hence the type is important.

Groovy provides a syntax for various type literals. There are three native collection literals in Groovy:

lists, using the [] literal

maps, using the [:] literal

ranges, using from..to (inclusive), from..<to (right exclusive), from<..to (left exclusive) and from<..<to (full exclusive)

The inferred type of a literal depends on the elements of the literal, as illustrated in the following table:

Literal Inferred type

be careful, a is a !

be careful, the key is a !

: uses the type of the bounds to infer the component type of the range

As you can see, with the noticeable exception of the IntRange , the inferred type makes use of generics types to describe the contents of a collection. In case the collection contains elements of different types, the type checker still performs type inference of the components, but uses the notion of least upper bound .

In Groovy, the least upper bound of two types A and B is defined as a type which:

superclass corresponds to the common super class of A and B

interfaces correspond to the interfaces implemented by both A and B

if A or B is a primitive type and that A isn’t equal to B , the least upper bound of A and B is the least upper bound of their wrapper types

If A and B only have one (1) interface in common and that their common superclass is Object , then the LUB of both is the common interface.

The least upper bound represents the minimal type to which both A and B can be assigned. So for example, if A and B are both String , then the LUB (least upper bound) of both is also String .

the LUB of and is
the LUB of and is their common super type,
the LUB of and is their only common interface,
the LUB of two identical interfaces is the interface itself
the LUB of and is their superclass
the LUB of two types which have nothing in common is

In those examples, the LUB is always representable as a normal, JVM supported, type. But Groovy internally represents the LUB as a type which can be more complex, and that you wouldn’t be able to use to define a variable for example. To illustrate this, let’s continue with this example:

What is the least upper bound of Bottom and SerializableFooImpl ? They don’t have a common super class (apart from Object ), but they do share 2 interfaces ( Serializable and Foo ), so their least upper bound is a type which represents the union of two interfaces ( Serializable and Foo ). This type cannot be defined in the source code, yet Groovy knows about it.

In the context of collection type inference (and generic type inference in general), this becomes handy, because the type of the components is inferred as the least upper bound. We can illustrate why this is important in the following example:

the interface defines a single method,
the interface defines a single method,
class implements both and but there’s no explicit interface extending both
same for
but defines an additional method
the type of is inferred as "list of the LUB of and `B`"
so it is possible to call which is defined on both and through the interface
and it is possible to call which is defined on both and through the interface
yet calling is a compile time error because it doesn’t belong to the LUB of and (only defined in )

The error message will look like:

which indicates that the exit method is neither defines on Greeter nor Salute , which are the two interfaces defined in the least upper bound of A and B .

In normal, non type checked, Groovy, you can write things like:

guard the method call with an check
make the call

The method call works because of dynamic dispatch (the method is selected at runtime). The equivalent code in Java would require to cast o to a Greeter before calling the greeting method, because methods are selected at compile time:

However, in Groovy, even if you add @TypeChecked (and thus activate type checking) on the doSomething method, the cast is not necessary. The compiler embeds instanceof inference that makes the cast optional.

Flow typing is an important concept of Groovy in type checked mode and an extension of type inference. The idea is that the compiler is capable of inferring the type of variables in the flow of the code, not just at initialization:

first, is declared using and assigned a
the compiler inferred that is a , so calling is allowed
is reassigned with a
calling passes compilation because the compiler knows that at this point, is a

So the type checker is aware of the fact that the concrete type of a variable is different over time. In particular, if you replace the last assignment with:

The type checker will now fail at compile time, because it knows that o is a double when toUpperCase is called, so it’s a type error.

It is important to understand that it is not the fact of declaring a variable with def that triggers type inference. Flow typing works for any variable of any type. Declaring a variable with an explicit type only constrains what you can assign to the variable:

is declared as an unchecked and assigned a list literal of `String`s
this line passes compilation because of flow typing: the type checker knows that is at this point a
but you can’t assign a to a so this is a type checking error

You can also note that even if the variable is declared without generics information, the type checker knows what is the component type. Therefore, such code would fail compilation:

is inferred as
so adding an to a is a compile-time error

Fixing this requires adding an explicit generic type to the declaration:

declared as and initialized with an empty list
elements added to the list conform to the declaration type of the list
so adding an to a is allowed

Flow typing has been introduced to reduce the difference in semantics between classic and static Groovy. In particular, consider the behavior of this code in Java:

is declared as an and assigned a
we call the method with
and print the result

In Java, this code will output Nope , because method selection is done at compile time and based on the declared types. So even if o is a String at runtime, it is still the Object version which is called, because o has been declared as an Object . To be short, in Java, declared types are most important, be it variable types, parameter types or return types.

In Groovy, we could write:

But this time, it will return 6 , because the method which is chosen at runtime , based on the actual argument types. So at runtime, o is a String so the String variant is used. Note that this behavior has nothing to do with type checking, it’s the way Groovy works in general: dynamic dispatch.

In type checked Groovy, we want to make sure the type checker selects the same method at compile time , that the runtime would choose. It is not possible in general, due to the semantics of the language, but we can make things better with flow typing. With flow typing, o is inferred as a String when the compute method is called, so the version which takes a String and returns an int is chosen. This means that we can infer the return type of the method to be an int , and not a String . This is important for subsequent calls and type safety.

So in type checked Groovy, flow typing is a very important concept, which also implies that if @TypeChecked is applied, methods are selected based on the inferred types of the arguments, not on the declared types. This doesn’t ensure 100% type safety, because the type checker may select a wrong method, but it ensures the closest semantics to dynamic Groovy.

A combination of flow typing and least upper bound inference is used to perform advanced type inference and ensure type safety in multiple situations. In particular, program control structures are likely to alter the inferred type of a variable:

if is true, is assigned a
if is false, is assigned a
calling is safe
but calling is not, so it’s a compile time error

When the type checker visits an if/else control structure, it checks all variables which are assigned in if/else branches and computes the least upper bound of all assignments. This type is the type of the inferred variable after the if/else block, so in this example, o is assigned a Top in the if branch and a Bottom in the else branch. The LUB of those is a Top , so after the conditional branches, the compiler infers o as being a Top . Calling methodFromTop will therefore be allowed, but not methodFromBottom .

The same reasoning exists with closures and in particular closure shared variables. A closure shared variable is a variable which is defined outside of a closure, but used inside a closure, as in this example:

a variable named is declared
is used from inside a closure. It is a .

Groovy allows developers to use those variables without requiring them to be final. This means that a closure shared variable can be reassigned inside a closure:

The problem is that a closure is an independent block of code that can be executed (or not) at any time. In particular, doSomething may be asynchronous, for example. This means that the body of a closure doesn’t belong to the main control flow. For that reason, the type checker also computes, for each closure shared variable, the LUB of all assignments of the variable, and will use that LUB as the inferred type outside of the scope of the closure, like in this example:

a closure-shared variable is first assigned a
inside the closure, it is assigned a
is allowed
is a compilation error

Here, it is clear that when methodFromBottom is called, there’s no guarantee, at compile-time or runtime that the type of o will effectively be a Bottom . There are chances that it will be, but we can’t make sure, because it’s asynchronous. So the type checker will only allow calls on the least upper bound , which is here a Top .

Closures and type inference

The type checker performs special inference on closures, resulting on additional checks on one side and improved fluency on the other side.

The first thing that the type checker is capable of doing is inferring the return type of a closure. This is simply illustrated in the following example:

a closure is defined, and it returns a string (more precisely a )
we call the closure and assign the result to a variable
the type checker inferred that the closure would return a string, so calling is allowed

As you can see, unlike a method which declares its return type explicitly, there’s no need to declare the return type of a closure: its type is inferred from the body of the closure.

It’s worth noting that return type inference is only applicable to closures. While the type checker could do the same on a method, it is in practice not desirable: in general , methods can be overridden and it is not statically possible to make sure that the method which is called is not an overridden version. So flow typing would actually think that a method returns something, while in reality, it could return something else, like illustrated in the following example:

class defines a method which effectively returns a
this will fail compilation because the return type of is (aka )
class extends and redefines , this type returning an

As you can see, if the type checker relied on the inferred return type of a method, with flow typing , the type checker could determine that it is ok to call toUpperCase . It is in fact an error , because a subclass can override compute and return a different object. Here, B#compute returns an int , so someone calling computeFully on an instance of B would see a runtime error. The compiler prevents this from happening by using the declared return type of methods instead of the inferred return type.

For consistency, this behavior is the same for every method, even if they are static or final.

In addition to the return type, it is possible for a closure to infer its parameter types from the context. There are two ways for the compiler to infer the parameter types:

through implicit SAM type coercion

through API metadata

To illustrate this, lets start with an example that will fail compilation due to the inability for the type checker to infer the parameter types:

the method accepts a and a
we call it with a and a
yet is not statically known as being a and compilation fails

In this example, the closure body contains it.age . With dynamic, not type checked code, this would work, because the type of it would be a Person at runtime. Unfortunately, at compile-time, there’s no way to know what is the type of it , just by reading the signature of inviteIf .

To be short, the type checker doesn’t have enough contextual information on the inviteIf method to determine statically the type of it . This means that the method call needs to be rewritten like this:

the type of needs to be declared explicitly

By explicitly declaring the type of the it variable, you can work around the problem and make this code statically checked.

For an API or framework designer, there are two ways to make this more elegant for users, so that they don’t have to declare an explicit type for the closure parameters. The first one, and easiest, is to replace the closure with a SAM type:

declare a interface with an method
now uses a instead of a
there’s no need to declare the type of the variable anymore
compiles properly, the type of is inferred from the method signature
By using this technique, we leverage the feature of Groovy. Whether you should use a or a really depends on what you need to do. In a lot of cases, using a SAM interface is enough, especially if you consider functional interfaces as they are found in Java 8. However, closures provide features that are not accessible to functional interfaces. In particular, closures can have a delegate, and owner and can be manipulated as objects (for example, cloned, serialized, curried, …​) before being called. They can also support multiple signatures (polymorphism). So if you need that kind of manipulation, it is preferable to switch to the most advanced type inference annotations which are described below.

The original issue that needs to be solved when it comes to closure parameter type inference, that is to say, statically determining the types of the arguments of a closure without having to have them explicitly declared, is that the Groovy type system inherits the Java type system, which is insufficient to describe the types of the arguments.

Groovy provides an annotation, @ClosureParams which is aimed at completing type information. This annotation is primarily aimed at framework and API developers who want to extend the capabilities of the type checker by providing type inference metadata. This is important if your library makes use of closures and that you want the maximum level of tooling support too.

Let’s illustrate this by fixing the original example, introducing the @ClosureParams annotation:

the closure parameter is annotated with
it’s not necessary to use an explicit type for , which is inferred

The @ClosureParams annotation minimally accepts one argument, which is named a type hint . A type hint is a class which is responsible for completing type information at compile time for the closure. In this example, the type hint being used is groovy.transform.stc.FirstParam which indicated to the type checker that the closure will accept one parameter whose type is the type of the first parameter of the method. In this case, the first parameter of the method is Person , so it indicates to the type checker that the first parameter of the closure is in fact a Person .

A second optional argument is named options . Its semantics depend on the type hint class. Groovy comes with various bundled type hints, illustrated in the table below:

Table 8. Predefined type hints
Type hint Polymorphic? Description and examples


No



No

and exist for all , and type hints.

No

signature and each of the parameter is specified as a value of the array using a fully-qualified type name or a primitive type.

Yes

single parameter, or two parameters corresponding to the key and the value.

that the first argument is a type, and infers the closure parameter types from the map actual key/value types.

Yes

abstract method.

be able to infer the types of the arguments if the arity of each method is different. In the example above, takes 2 arguments and takes 1 argument, so the type checker can infer the argument types based on the number of arguments. But see the optional resolver class attribute discussed next.

Yes

argument. The argument consists of an array of comma-separated non-primitive types. Each element of the array corresponds to a single signature, and each comma in an element separate parameters of the signature. In short, this is the most generic type hint, and each string of the map is as if it was a signature literal. While being very powerful, this type hint must be avoided if you can because it increases the compilation times due to the necessity of parsing the type signatures.

:

or a :

or a pair :

Even though you use , or as a type hint, it doesn’t strictly mean that the argument which will be passed to the closure be the first (resp. second, third) argument of the method call. It only means that the of the parameter of the closure will be the as the type of the first (resp. second, third) argument of the method call.

In short, the lack of the @ClosureParams annotation on a method accepting a Closure will not fail compilation. If present (and it can be present in Java sources as well as Groovy sources), then the type checker has more information and can perform additional type inference. This makes this feature particularly interesting for framework developers.

A third optional argument is named conflictResolutionStrategy . It can reference a class (extending from ClosureSignatureConflictResolver ) that can perform additional resolution of parameter types if more than one are found after initial inference calculations are complete. Groovy comes with a default type resolver which does nothing, and another which selects the first signature if multiple are found. The resolver is only invoked if more than one signature is found and is by design a post processor. Any statements which need injected typing information must pass one of the parameter signatures determined through type hints. The resolver then picks among the returned candidate signatures.

The @DelegatesTo annotation is used by the type checker to infer the type of the delegate. It allows the API designer to instruct the compiler what is the type of the delegate and the delegation strategy. The @DelegatesTo annotation is discussed in a specific section .

Static compilation

In the type checking section , we have seen that Groovy provides optional type checking thanks to the @TypeChecked annotation. The type checker runs at compile time and performs a static analysis of dynamic code. The program will behave exactly the same whether type checking has been enabled or not. This means that the @TypeChecked annotation is neutral in regard to the semantics of a program. Even though it may be necessary to add type information in the sources so that the program is considered type safe, in the end, the semantics of the program are the same.

While this may sound fine, there is actually one issue with this: type checking of dynamic code, done at compile time, is by definition only correct if no runtime specific behavior occurs. For example, the following program passes type checking:

There are two compute methods. One accepts a String and returns an int , the other accepts an int and returns a String . If you compile this, it is considered type safe: the inner compute('foobar') call will return an int , and calling compute on this int will in turn return a String .

Now, before calling test() , consider adding the following line:

Using runtime metaprogramming, we’re actually modifying the behavior of the compute(String) method, so that instead of returning the length of the provided argument, it will return a Date . If you execute the program, it will fail at runtime. Since this line can be added from anywhere, in any thread, there’s absolutely no way for the type checker to statically make sure that no such thing happens. In short, the type checker is vulnerable to monkey patching. This is just one example, but this illustrates the concept that doing static analysis of a dynamic program is inherently wrong.

The Groovy language provides an alternative annotation to @TypeChecked which will actually make sure that the methods which are inferred as being called will effectively be called at runtime. This annotation turns the Groovy compiler into a static compiler , where all method calls are resolved at compile time and the generated bytecode makes sure that this happens: the annotation is @groovy.transform.CompileStatic .

The @CompileStatic annotation can be added anywhere the @TypeChecked annotation can be used, that is to say on a class or a method. It is not necessary to add both @TypeChecked and @CompileStatic , as @CompileStatic performs everything @TypeChecked does, but in addition triggers static compilation.

Let’s take the example which failed , but this time let’s replace the @TypeChecked annotation with @CompileStatic :

This is the only difference. If we execute this program, this time, there is no runtime error. The test method became immune to monkey patching, because the compute methods which are called in its body are linked at compile time, so even if the metaclass of Computer changes, the program still behaves as expected by the type checker .

There are several benefits of using @CompileStatic on your code:

type safety

immunity to monkey patching

performance improvements

The performance improvements depend on the kind of program you are executing. If it is I/O bound, the difference between statically compiled code and dynamic code is barely noticeable. On highly CPU intensive code, since the bytecode which is generated is very close, if not equal, to the one that Java would produce for an equivalent program, the performance is greatly improved.

Using the version of Groovy, which is accessible to people using JDK 7 and above, the performance of the dynamic code should be very close to the performance of statically compiled code. Sometimes, it can even be faster! There is only one way to determine which version you should choose: measuring. The reason is that depending on your program the JVM that you use, the performance can be significantly different. In particular, the version of Groovy is very sensitive to the JVM version in use.

1.6.7. Type checking extensions

Writing a type checking extension.

Despite being a dynamic language, Groovy can be used with a static type checker at compile time, enabled using the @TypeChecked annotation. In this mode, the compiler becomes more verbose and throws errors for, example, typos, non-existent methods, etc. This comes with a few limitations though, most of them coming from the fact that Groovy remains inherently a dynamic language. For example, you wouldn’t be able to use type checking on code that uses the markup builder:

In the previous example, none of the html , head , body or p methods exist. However if you execute the code, it works because Groovy uses dynamic dispatch and converts those method calls at runtime. In this builder, there’s no limitation about the number of tags that you can use, nor the attributes, which means there is no chance for a type checker to know about all the possible methods (tags) at compile time, unless you create a builder dedicated to HTML for example.

Groovy is a platform of choice when it comes to implement internal DSLs. The flexible syntax, combined with runtime and compile-time metaprogramming capabilities make Groovy an interesting choice because it allows the programmer to focus on the DSL rather than on tooling or implementation. Since Groovy DSLs are Groovy code, it’s easy to have IDE support without having to write a dedicated plugin for example.

In a lot of cases, DSL engines are written in Groovy (or Java) then user code is executed as scripts, meaning that you have some kind of wrapper on top of user logic. The wrapper may consist, for example, in a GroovyShell or GroovyScriptEngine that performs some tasks transparently before running the script (adding imports, applying AST transforms, extending a base script,…). Often, user written scripts come to production without testing because the DSL logic comes to a point where  any user may write code using the DSL syntax. In the end, a user may just ignore that what they write is actually  code . This adds some challenges for the DSL implementer, such as securing execution of user code or, in this case, early reporting of errors.

For example, imagine a DSL which goal is to drive a rover on Mars remotely. Sending a message to the rover takes around 15 minutes. If the rover executes the script and fails with an error (say a typo), you have two problems:

first, feedback comes only after 30 minutes (the time needed for the rover to get the script and the time needed to receive the error)

second, some portion of the script has been executed and you may have to change the fixed script significantly (implying that you need to know the current state of the rover…)

Type checking extensions is a mechanism that will allow the developer of a DSL engine to make those scripts safer by applying the same kind of checks that static type checking allows on regular groovy classes.

The principle, here, is to fail early, that is to say fail compilation of scripts as soon as possible, and if possible provide feedback to the user (including nice error messages).

In short, the idea behind type checking extensions is to make the compiler aware of all the runtime metaprogramming tricks that the DSL uses, so that scripts can benefit the same level of compile-time checks as a verbose statically compiled code would have. We will see that you can go even further by performing checks that a normal type checker wouldn’t do, delivering powerful compile-time checks for your users.

The  @TypeChecked annotation supports an attribute named  extensions . This parameter takes an array of strings corresponding to a list of type checking extensions scripts . Those scripts are found at  compile time on classpath. For example, you would write:

In that case, the  foo methods would be type checked with the rules of the normal type checker completed by those found in the  myextension.groovy script. Note that while internally the type checker supports multiple mechanisms to implement type checking extensions (including plain old java code), the recommended way is to use those type checking extension scripts.

The idea behind type checking extensions is to use a DSL to extend the type checker capabilities. This DSL allows you to hook into the compilation process, more specifically the type checking phase, using an "event-driven" API. For example, when the type checker enters a method body, it throws a  beforeVisitMethod event that the extension can react to:

Imagine that you have this rover DSL at hand. A user would write:

If you have a class defined as such:

The script can be type checked before being executed using the following script:

a compiler configuration adds the annotation to all classes
use the configuration in a
so that scripts compiled using the shell are compiled with without the user having to add it explicitly

Using the compiler configuration above, we can apply  @TypeChecked transparently to the script. In that case, it will fail at compile time:

Now, we will slightly update the configuration to include the ``extensions'' parameter:

Then add the following to your classpath:

Here, we’re telling the compiler that if an unresolved variable is found and that the name of the variable is  robot , then we can make sure that the type of this variable is Robot .

Type checking extensions API

The type checking API is a low level API, dealing with the Abstract Syntax Tree. You will have to know your AST well to develop extensions, even if the DSL makes it much easier than just dealing with AST code from plain Java or Groovy.

The type checker sends the following events, to which an extension script can react:

is called even if you did and set the handled flag to true.

, this event is sent when the type checker cannot find a target method for a method call (instance or static). It gives you the chance to intercept the error before it is sent to the user, but also set the target method.For this, you need to return a list of . In most situations, you would either return: an empty list, meaning that you didn’t find a corresponding method, a list with exactly one element, saying that there’s no doubt about the target methodIf you return more than one MethodNode, then the compiler would throw an error to the user stating that the method call is ambiguous, listing the possible methods.For convenience, if you want to return only one method, you are allowed to return it directly instead of wrapping it into a list.

. It can help you define the scope of your extension, or you can even totally replace the visit of the type checker with a custom type checking implementation. For that, you would have to set the flag to . 

and any inner/anonymous class defined in the same class with is not skipped.

, because in that case it is possible that assigning a variable of one type to a property of another type is handled through that runtime mechanism. In that case, you can help the type checker just by telling it that the assignment is valid (using set to ).

property).

Of course, an extension script may consist of several blocks, and you can have multiple blocks responding to the same event. This makes the DSL look nicer and easier to write. However, reacting to events is far from sufficient. If you know you can react to events, you also need to deal with the errors, which implies several helper methods that will make things easier.

Working with extensions

The DSL relies on a support class called  org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport . This class itself extends  org.codehaus.groovy.transform.stc.TypeCheckingExtension . Those two classes define a number of helper methods that will make working with the AST easier, especially regarding type checking. One interesting thing to know is that you  have access to the type checker . This means that you can programmatically call methods of the type checker, including those that allow you to throw compilation errors .

The extension script delegates to the  org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport class, meaning that you have direct access to the following variables:

context : the type checker context, of type  org.codehaus.groovy.transform.stc.TypeCheckingContext

typeCheckingVisitor : the type checker itself, a  org.codehaus.groovy.transform.stc.StaticTypeCheckingVisitor instance

generatedMethods : a list of "generated methods", which is in fact the list of "dummy" methods that you can create inside a type checking extension using the  newMethod calls

The type checking context contains a lot of information that is useful in context for the type checker. For example, the current stack of enclosing method calls, binary expressions, closures, … This information is in particular important if you have to know where you are when an error occurs and that you want to handle it.

In addition to facilities provided by GroovyTypeCheckingExtensionSupport and StaticTypeCheckingVisitor , a type-checking DSL script imports static members from org.codehaus.groovy.ast.ClassHelper and org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport granting access to common types via OBJECT_TYPE , STRING_TYPE , THROWABLE_TYPE , etc. and checks like missesGenericsTypes(ClassNode) , isClassClassNodeWrappingConcreteType(ClassNode) and so on.

Handling class nodes is something that needs particular attention when you work with a type checking extension. Compilation works with an abstract syntax tree (AST) and the tree may not be complete when you are type checking a class. This also means that when you refer to types, you must not use class literals such as  String or  HashSet , but to class nodes representing those types. This requires a certain level of abstraction and understanding how Groovy deals with class nodes. To make things easier, Groovy supplies several helper methods to deal with class nodes. For example, if you want to say "the type for String", you can write:

You would also note that there is a variant of  classNodeFor that takes a  String as an argument, instead of a  Class . In general, you should  not use that one, because it would create a class node for which the name is String , but without any method, any property, … defined on it. The first version returns a class node that is  resolved but the second one returns one that is  not . So the latter should be reserved for very special cases.

The second problem that you might encounter is referencing a type which is not yet compiled. This may happen more often than you think. For example, when you compile a set of files together. In that case, if you want to say "that variable is of type Foo" but Foo is not yet compiled, you can still refer to the Foo class node using  lookupClassNodeFor :

Say that you know that variable  foo is of type  Foo and you want to tell the type checker about it. Then you can use the  storeType method, which takes two arguments: the first one is the node for which you want to store the type and the second one is the type of the node. If you look at the implementation of  storeType , you would see that it delegates to the type checker equivalent method, which itself does a lot of work to store node metadata. You would also see that storing the type is not limited to variables: you can set the type of any expression.

Likewise, getting the type of an AST node is just a matter of calling  getType on that node. This would in general be what you want, but there’s something that you must understand:

getType returns the  inferred type of an expression. This means that it will not return, for a variable declared of type  Object the class node for  Object , but the inferred type of this variable  at this point of the code (flow typing)

if you want to access the origin type of a variable (or field/parameter), then you must call the appropriate method on the AST node

To throw a type checking error, you only have to call the addStaticTypeError method which takes two arguments:

a  message which is a string that will be displayed to the end user

an AST node responsible for the error. It’s better to provide the best suiting AST node because it will be used to retrieve the line and column numbers

It is often required to know the type of an AST node. For readability, the DSL provides a special isXXXExpression method that will delegate to x instance of XXXExpression . For example, instead of writing:

you can just write:

When you perform type checking of dynamic code, you may often face the case when you know that a method call is valid but there is no "real" method behind it. As an example, take the Grails dynamic finders. You can have a method call consisting of a method named  findByName(…) . As there’s no  findByName method defined in the bean, the type checker would complain. Yet, you would know that this method wouldn’t fail at runtime, and you can even tell what is the return type of this method. For this case, the DSL supports two special constructs that consist of phantom methods . This means that you will return a method node that doesn’t really exist but is defined in the context of type checking. Three methods exist:

newMethod(String name, Class returnType)

newMethod(String name, ClassNode returnType)

newMethod(String name, Callable<ClassNode> return Type)

All three variants do the same: they create a new method node which name is the supplied name and define the return type of this method. Moreover, the type checker would add those methods in the  generatedMethods list (see  isGenerated below). The reason why we only set a name and a return type is that it is only what you need in 90% of the cases. For example, in the  findByName example upper, the only thing you need to know is that  findByName wouldn’t fail at runtime, and that it returns a domain class. The  Callable version of return type is interesting because it defers the computation of the return type when the type checker actually needs it. This is interesting because in some circumstances, you may not know the actual return type when the type checker demands it, so you can use a closure that will be called each time  getReturnType is called by the type checker on this method node. If you combine this with deferred checks, you can achieve pretty complex type checking including handling of forward references.

Should you need more than the name and return type, you can always create a new  MethodNode by yourself.

Scoping is very important in DSL type checking and is one of the reasons why we couldn’t use a  pointcut based approach to DSL type checking. Basically, you must be able to define very precisely when your extension applies and when it does not. Moreover, you must be able to handle situations that a regular type checker would not be able to handle, such as forward references:

Say for example that you want to handle a builder:

Your extension, then, should only be active once you’ve entered the  foo method, and inactive outside this scope. But you could have complex situations like multiple builders in the same file or embedded builders (builders in builders). While you should not try to fix all this from start (you must accept limitations to type checking), the type checker does offer a nice mechanism to handle this: a scoping stack, using the  newScope and  scopeExit methods.

newScope creates a new scope and puts it on top of the stack

scopeExits pops a scope from the stack

A scope consists of:

a parent scope

a map of custom data

If you want to look at the implementation, it’s simply a LinkedHashMap ( org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport.TypeCheckingScope ), but it’s quite powerful. For example, you can use such a scope to store a list of closures to be executed when you exit the scope. This is how you would handle forward references: 

That is to say, that if at some point you are not able to determine the type of an expression, or that you are not able to check at this point that an assignment is valid or not, you can still make the check later… This is a very powerful feature. Now,  newScope and  scopeExit provide some interesting syntactic sugar:

At anytime in the DSL, you can access the current scope using  getCurrentScope() or more simply  currentScope :

The general schema would then be:

determine a pointcut where you push a new scope on stack and initialize custom variables within this scope

using the various events, you can use the information stored in your custom scope to perform checks, defer checks,…

determine a pointcut where you exit the scope, call  scopeExit and eventually perform additional checks

For the complete list of helper methods, please refer to the  org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport and  org.codehaus.groovy.transform.stc.TypeCheckingExtension classes. However, take special attention to those methods:

isDynamic : takes a VariableExpression as argument and returns true if the variable is a DynamicExpression, which means, in a script, that it wasn’t defined using a type or def .

isGenerated : takes a MethodNode as an argument and tells if the method is one that was generated by the type checker extension using the  newMethod method

isAnnotatedBy : takes an AST node and a Class (or ClassNode), and tells if the node is annotated with this class. For example: isAnnotatedBy(node, NotNull)

getTargetMethod : takes a method call as argument and returns the  MethodNode that the type checker has determined for it

delegatesTo : emulates the behaviour of the  @DelegatesTo annotation. It allows you to tell that the argument will delegate to a specific type (you can also specify the delegation strategy)

Advanced type checking extensions

All the examples above use type checking scripts. They are found in source form in classpath, meaning that:

a Groovy source file, corresponding to the type checking extension, is available on compilation classpath

this file is compiled by the Groovy compiler for each source unit being compiled (often, a source unit corresponds to a single file)

It is a very convenient way to develop type checking extensions, however it implies a slower compilation phase, because of the compilation of the extension itself for each file being compiled. For those reasons, it can be practical to rely on a precompiled extension. You have two options to do this:

write the extension in Groovy, compile it, then use a reference to the extension class instead of the source

write the extension in Java, compile it, then use a reference to the extension class

Writing a type checking extension in Groovy is the easiest path. Basically, the idea is that the type checking extension script becomes the body of the main method of a type checking extension class, as illustrated here:

extending the class is the easiest
then the extension code needs to go inside the method
and you can use the very same events as an extension written in source form

Setting up the extension is very similar to using a source form extension:

The difference is that instead of using a path in classpath, you just specify the fully qualified class name of the precompiled extension.

In case you really want to write an extension in Java, then you will not benefit from the type checking extension DSL. The extension above can be rewritten in Java this way:

extend the class
then override the methods as required

It is totally possible to use the @Grab annotation in a type checking extension. This means you can include libraries that would only be available at compile time. In that case, you must understand that you would increase the time of compilation significantly (at least, the first time it grabs the dependencies).

A type checking extension is just a script that need to be on classpath. As such, you can share it as is, or bundle it in a jar file that would be added to classpath.

While you can configure the compiler to transparently add type checking extensions to your script, there is currently no way to apply an extension transparently just by having it on classpath.

Type checking extensions are used with @TypeChecked but can also be used with @CompileStatic . However, you must be aware that:

a type checking extension used with @CompileStatic will in general not be sufficient to let the compiler know how to generate statically compilable code from "unsafe" code

it is possible to use a type checking extension with @CompileStatic just to enhance type checking, that is to say introduce more compilation errors, without actually dealing with dynamic code

Let’s explain the first point, which is that even if you use an extension, the compiler will not know how to compile your code statically: technically, even if you tell the type checker what is the type of a dynamic variable, for example, it would not know how to compile it. Is it getBinding('foo') , getProperty('foo') , delegate.getFoo() ,…? There’s absolutely no direct way to tell the static compiler how to compile such code even if you use a type checking extension (that would, again, only give hints about the type).

One possible solution for this particular example is to instruct the compiler to use mixed mode compilation . The more advanced one is to use AST transformations during type checking but it is far more complex.

Type checking extensions allow you to help the type checker where it fails, but it also allows you to fail where it doesn’t. In that context, it makes sense to support extensions for  @CompileStatic too. Imagine an extension that is capable of type checking SQL queries. In that case, the extension would be valid in both dynamic and static context, because without the extension, the code would still pass.

In the previous section, we highlighted the fact that you can activate type checking extensions with @CompileStatic . In that context, the type checker would not complain anymore about some unresolved variables or unknown method calls, but it would still wouldn’t know how to compile them statically.

Mixed mode compilation offers a third way, which is to instruct the compiler that whenever an unresolved variable or method call is found, then it should fall back to a dynamic mode. This is possible thanks to type checking extensions and a special makeDynamic call.

To illustrate this, let’s come back to the Robot example:

And let’s try to activate our type checking extension using @CompileStatic instead of @TypeChecked :

Apply transparently
Activate the type checking extension

The script will run fine because the static compiler is told about the type of the robot variable, so it is capable of making a direct call to move . But before that, how did the compiler know how to get the robot variable? In fact by default, in a type checking extension, setting handled=true on an unresolved variable will automatically trigger a dynamic resolution, so in this case you don’t have anything special to make the compiler use a mixed mode. However, let’s slightly update our example, starting from the robot script:

Here you can notice that there is no reference to robot anymore. Our extension will not help then because we will not be able to instruct the compiler that move is done on a Robot instance. This example of code can be executed in a totally dynamic way thanks to the help of a groovy.util.DelegatingScript :

we configure the compiler to use a as the base class
the script source needs to be parsed and will return an instance of
we can then call to use a as the delegate of the script
then execute the script. will be directly executed on the delegate

If we want this to pass with @CompileStatic , we have to use a type checking extension, so let’s update our configuration:

apply transparently
use an alternate type checking extension meant to recognize the call to

Then in the previous section we have learnt how to deal with unrecognized method calls, so we are able to write this extension:

if the call is a method call (not a static method call)
that this call is made on "implicit this" (no explicit )
that the method being called is
and that the call is done with a single argument
and that argument is of type
then tell the type checker that the call is valid
and that the return type of the call is

If you try to execute this code, then you could be surprised that it actually fails at runtime:

The reason is very simple: while the type checking extension is sufficient for @TypeChecked , which does not involve static compilation, it is not enough for @CompileStatic which requires additional information. In this case, you told the compiler that the method existed, but you didn’t explain to it what method it is in reality, and what is the receiver of the message (the delegate).

Fixing this is very easy and just implies replacing the newMethod call with something else:

tell the compiler that the call should be make dynamic

The makeDynamic call does 3 things:

it returns a virtual method just like newMethod

automatically sets the handled flag to true for you

but also marks the call to be done dynamically

So when the compiler will have to generate bytecode for the call to move , since it is now marked as a dynamic call, it will fall back to the dynamic compiler and let it handle the call. And since the extension tells us that the return type of the dynamic call is a Robot , subsequent calls will be done statically!

Some would wonder why the static compiler doesn’t do this by default without an extension. It is a design decision:

if the code is statically compiled, we normally want type safety and best performance

so if unrecognized variables/method calls are made dynamic, you loose type safety, but also all support for typos at compile time!

In short, if you want to have mixed mode compilation, it has to be explicit, through a type checking extension, so that the compiler, and the designer of the DSL, are totally aware of what they are doing.

makeDynamic can be used on 3 kind of AST nodes:

a method node ( MethodNode )

a variable ( VariableExpression )

a property expression ( PropertyExpression )

If that is not enough, then it means that static compilation cannot be done directly and that you have to rely on AST transformations.

Type checking extensions look very attractive from an AST transformation design point of view: extensions have access to context like inferred types, which is often nice to have. And an extension has a direct access to the abstract syntax tree. Since you have access to the AST, there is nothing in theory that prevents you from modifying the AST. However, we do not recommend you to do so, unless you are an advanced AST transformation designer and well aware of the compiler internals:

First of all, you would explicitly break the contract of type checking, which is to annotate, and only annotate the AST. Type checking should  not modify the AST tree because you wouldn’t be able to guarantee anymore that code without the  @TypeChecked annotation behaves the same without the annotation.

If your extension is meant to work with  @CompileStatic , then you  can modify the AST because this is indeed what  @CompileStatic will eventually do. Static compilation doesn’t guarantee the same semantics at dynamic Groovy so there is effectively a difference between code compiled with  @CompileStatic and code compiled with  @TypeChecked . It’s up to you to choose whatever strategy you want to update the AST, but probably using an AST transformation that runs before type checking is easier.

if you cannot rely on a transformation that kicks in before the type checker, then you must be very careful

The type checking phase is the last phase running in the compiler before bytecode generation. All other AST transformations run before that and the compiler does a very good job at "fixing" incorrect AST generated before the type checking phase. As soon as you perform a transformation during type checking, for example directly in a type checking extension, then you have to do all this work of generating a 100% compiler compliant abstract syntax tree by yourself, which can easily become complex. That’s why we do not recommend to go that way if you are beginning with type checking extensions and AST transformations.

Examples of real life type checking extensions are easy to find. You can download the source code for Groovy and take a look at the TypeCheckingExtensionsTest class which is linked to various extension scripts .

An example of a complex type checking extension can be found in the Markup Template Engine source code: this template engine relies on a type checking extension and AST transformations to transform templates into fully statically compiled code. Sources for this can be found here .

2.1. Running Groovy from the commandline

groovy invokes the Groovy command line processor. It allows you to run inline Groovy expressions, and scripts, tests or application within groovy files. It plays a similar role to java in the Java world but handles inline scripts and rather than invoking class files, it is normally called with scripts and will automatically call the Groovy compiler as needed.

The easiest way to run a Groovy script, test or application is to run the following command at your shell prompt:

The .groovy part is optional. The groovy command supports a number of command line switches:

Short version Long version Description Example

-a

--autosplit <splitPattern>

split lines using splitPattern (default '\s') using implicit 'split' variable

-b

--basescript <class>

Base class name for scripts (must derive from Script)

-c

--encoding <charset>

specify the encoding of the files

-cp <path>

-classpath <path>
--classpath <path>

Specify the compilation classpath. Must be the first argument.

groovy -cp lib/dep.jar MyScript

--configscript <path>

Advanced compiler configuration script

groovy --configscript config/config.groovy src/Person.groovy

-D

--define <name=value>

define a system property

-d

--debug

debug mode will print out full stack traces

--disableopt <optlist>

disables one or all optimization elements.
optlist can be a comma separated list with the elements:
all (disables all optimizations),
int (disable any int based optimizations)

-e <script>

specify an inline command line script

groovy -e "println new Date()"

-h

--help

Displays usage information for the command line groovy command

groovy --help

-i <extension>

modify files in place; create backup if extension is given (e.g. '.bak')

-l <port>

listen on a port and process inbound lines (default: 1960)

-n

process files line by line using implicit 'line' variable

-p

process files line by line and print result (see also -n)

-v

--version

display the Groovy and JVM versions

groovy -v

-pa

--parameters

Generates metadata for reflection on method parameter names on JDK 8 and above. Defaults to false.

groovy --parameters Person.groovy

-pr

--enable-preview

Enable preview Java features (jdk12+ only).

groovy --enable-preview Person.groovy

2.2. Compiling Groovy

groovyc is the Groovy compiler command line tool. It allows you to compile Groovy sources into bytecode. It plays the same role as javac in the Java world. The easiest way to compile a Groovy script or class is to run the following command:

This will produce a MyClass.class file (as well as other .class files depending on the contents of the source). groovyc supports a number of command line switches:

Short version Long version Description Example

-cp

-classpath, --classpath

Specify the compilation classpath. Must be the first argument.

groovyc -cp lib/dep.jar MyClass.groovy

--sourcepath

Directory where to find source files. Not used anymore. Specifying this parameter will have no effect.

--temp

Temporary directory for the compiler

--encoding

Encoding of the source files

groovyc --encoding utf-8 script.groovy

--help

Displays help for the command line groovyc tool

groovyc --help

-d

Specify where to place generated class files.

groovyc -d target Person.groovy

-v

--version

Displays the compiler version

groovyc -v

-e

--exception

Displays the stack trace in case of compilation error

groovyc -e script.groovy

-j

--jointCompilation*

Enables joint compilation

groovyc -j A.groovy B.java

-b

--basescript

Base class name for scripts (must derive from Script)

--configscript

Advanced compiler configuration script

groovyc --configscript config/config.groovy src/Person.groovy

-Jproperty=value

Properties to be passed to if joint compilation is enabled

groovyc -j -Jtarget=1.6 -Jsource=1.6 A.groovy B.java

-Fflag

Flags to be passed to if joint compilation is enabled

groovyc -j -Fnowarn A.groovy B.java

-pa

--parameters

Generates metadata for reflection on method parameter names. Requires Java 8+.

groovyc --parameters Person.groovy

-pr

--enable-preview

Enable preview Java features (jdk12+ only).

groovy --enable-preview Person.groovy

@argfile

Read options and source files from specified file.

groovyc @conf/args

Notes: * for a full description of joint compilation, see the joint compilation section .

See the groovyc Ant task documentation. It allows the Groovy compiler to be invoked from Apache Ant .

Gant is a tool for scripting Ant tasks using Groovy instead of XML to specify the logic. As such, it has exactly the same features as the Groovyc Ant task.

Gradle is a build tool that allows you to leverage the flexibility of Ant , while keeping the simplicity of convention over configuration that tools like Maven offer. Builds are specified using a Groovy DSL, which offers great flexibility and succinctness.

2.2.5. Maven integration

There are several approaches to compiling Groovy code in your Maven projects. GMavenPlus is the most flexible and feature rich, but like most Groovy compiler tools, it can have difficulties with joint Java-Groovy projects (for the same reason GMaven and Gradle can have issues). The Groovy-Eclipse compiler plugin for Maven sidesteps the joint compilation issues. Read this for a deeper discussion of the benefits and disadvantages of the two approaches.

A third approach is to use Maven’s Ant plugin to compile a groovy project. Note that the Ant plugin is bound to the compile and test-compile phases of the build in the example below. It will be invoked during these phases and the contained tasks will be carried out which runs the Groovy compiler over the source and test directories. The resulting Java classes will coexist with and be treated like any standard Java classes compiled from Java source and will appear no different to the JRE, or the JUnit runtime.

This assumes you have a Maven project setup with groovy subfolders as peers to the java src and test subfolders. You can use the java / jar archetype to set this up then rename the java folders to groovy or keep the java folders and just create groovy peer folders. There exists, also a groovy plugin which has not been tested or used in production. After defining the build section as in the above example, you can invoke the typical Maven build phases normally. For example, mvn test will execute the test phase, compiling Groovy source and Groovy test source and finally executing the unit tests. If you run mvn jar it will execute the jar phase bundling up all of your compiled production classes into a jar after all the unit tests pass. For more detail on Maven build phases consult the Maven2 documentation.

GMaven and GMavenPlus

GMaven is the original Maven plugin for Groovy, supporting both compiling and scripting Groovy.

You should be aware that GMaven is not supported anymore and can have difficulties with joint compilation . GMavenPlus can be a good replacement, but if you are having problems with joint compilation, you might consider the Groovy Eclipse maven plugin .

GMavenPlus is a rewrite of GMaven and is in active development. It supports most of the features of GMaven (a couple notable exceptions being mojo Javadoc tags and support for older Groovy versions). Its joint compilation uses stubs (which means it has the same potential issues as GMaven and Gradle ). The main advantages over its predecessor are that it supports recent Groovy versions, InvokeDynamic, Groovy on Android, GroovyDoc, and configuration scripts.

Unlike the name might seem to suggest, GMaven 2 is not aimed at replacing GMaven . In fact, it removes the non-scripting features of the GMaven plugin. It has not yet had any release and appears to be inactive currently.

Groovy-Eclipse provides a compiler plugin for Maven. Using the compiler plugin, it is possible to compile your maven projects using the Groovy-Eclipse compiler. One feature unavailable elsewhere is stubless joint compilation.

Joint compilation means that the Groovy compiler will parse the Groovy source files, create stubs for all of them, invoke the Java compiler to compile the stubs along with Java sources, and then continue compilation in the normal Groovy compiler way. This allows mixing of Java and Groovy files without constraint.

Joint compilation can be enabled using the -j flag with the command-line compiler, or using a nested tag and all the attributes and further nested tags as required for the Ant task.

It is important to know that if you don’t enable joint compilation and try to compile Java source files with the Groovy compiler, the Java source files will be compiled as if they were Groovy sources. In some situations, this might work since most of the Java syntax is compatible with Groovy, but there are a number of places where semantics could be different.

It is possible to write an Android application in Groovy. However this requires a special version of the compiler, meaning that you cannot use the regular groovyc tool to target Android bytecode. In particular, Groovy provides specific JAR files for Android, which have a classifier of grooid . In order to make things easier, a Gradle plugin adds support for the Groovy language in the Android Gradle toolchain.

The plugin can be applied like this:

Then you will need to add a dependency on the grooid version of the Groovy compiler:

Note that if a Groovy jar does not provide a grooid classifier alternative, then it means that the jar is directly compatible with Android. In that case, you can add the dependency directly like this:

Note that the transitive=false parameter for groovy-json will let Gradle download the JSON support jar without adding a dependency onto the normal jar of Groovy.

Please make sure to go to the plugin homepage in order to find the latest documentation and version.

2.3. Groovysh, the Groovy shell

2.3.1. groovy : groovy shell.

The Groovy Shell, aka. groovysh is a command-line application which allows easy access to evaluate Groovy expressions, define classes and run simple experiments.

No need for go command to execute buffer.

Rich cross-platform edit-line editing, history and completion thanks to JLine2 .

ANSI colors (prompt, exception traces, etc).

Simple, yet robust, command system with online help, user alias support and more.

User profile support

The shell supports several options to control verbosity, ANSI coloring and other features.

Evaluating Expressions

When a complete expression is found, it is compiled and evaluated. The result of the evaluation is stored into the _ variable.

Multi-line Expressions

Multi-line/complex expressions (like closure or class definitions) may be defined over several lines. When the shell detects that it has a complete expression it will compile and evaluate it.

Shell variables are all untyped (i.e. no def or other type information).

This will set a shell variable:

But, this will evaluate a local variable and will not be saved to the shell’s environment:

This behavior can be changed by activating interpreter mode .

Functions can be defined in the shell, and will be saved for later use.

Defining a function is easy:

And then using it is as one might expect:

Internally the shell creates a closure to encapsulate the function and then binds the closure to a variable. So variables and functions share the same namespace.

The shell has a number of different commands, which provide rich access to the shell’s environment.

Commands all have a name and a shortcut (which is something like \h ). Commands may also have some predefined system aliases . Users may also create their own aliases.

Recognized Commands

Display the list of commands (and aliases) or the help text for specific command.

The Command List

Help for a Command

While in the interactive shell, you can ask for help for any command to get more details about its syntax or function. Here is an example of what happens when you ask for help for the help command:

Exit the shell.

This is the only way to exit the shell. Well, you can still CTRL-C , but the shell will complain about an abnormal shutdown of the JVM.

Add a custom import which will be included for all shell evaluations.

This command can be given at any time to add new imports.

Grab a dependency (Maven, Ivy, etc.) from Internet sources or cache, and add it to the Groovy Shell environment.

This command can be given at any time to add new dependencies.

Display the contents of the current buffer.

This only displays the buffer of an incomplete expression. Once the expression is complete, the buffer is reset. The prompt will update to show the size of the current buffer as well.

Clears the current buffer, resetting the prompt counter to 000. Can be used to recover from compilation errors.

Show variables, classes or preferences or imports.

show variables

show classes

show imports

show preferences

Opens the GUI object browser to inspect a variable or the result of the last evaluation.

Purges objects from the shell.

purge variables

purge classes

purge imports

purge preferences

Edit the current buffer in an external editor.

Currently only works on UNIX systems which have the EDITOR environment variable set, or have configured the editor preference.

Load one or more files (or urls) into the buffer.

Saves the buffer’s contents to a file.

Record the current session to a file.

record start

record stop

record status

Display, manage and recall edit-line history.

history show

history recall

history flush

history clear

Create an alias.

Opens a browser with documentation for the provided class.

For example, we can get both the Javadoc and GDK enhancements doc for java.util.List (shown running on JDK17):

This will print the documentation URLs found and open two windows (or tabs, depending on your browser):

one for the JDK documentation

one for the GDK documentation

By default, for Java classes, the java.base module is assumed. You can specify an optional module for other cases (shown running on JDK17):

For backwards compatibility, if no module is specified when searching for Java classes, and no class is found in the java.base module, an additional attempt is made to find documentation for the class in the JDK8 (pre-module) Javadoc:

To get the Groovydoc for groovy.ant.AntBuilder and groovy.xml.XmlSlurper :

To get both the Groovydoc and GDK enhancements doc for groovy.lang.Closure and groovy.sql.GroovyResultSet :

Documentation is also available for the GDK enhancements to primitive arrays and arrays of arrays:

In contexts where opening a browser may not be desirable, e.g. on a CI server, this command can be disabled by setting the system property to .

Set or list preferences.

Preferences

Some aspects of groovysh behaviors can be customized by setting preferences. Preferences are set using the set command or the := shortcut.

Recognized Preferences

Allows the use of typed variables (i.e. def or other type information):

It’s especially useful for copy&pasting code from tutorials etc. into the running session.

Set the shell’s verbosity level. Expected to be one of:

Default is INFO .

If this preference is set to an invalid value, then the previous setting will be used, or if there is none, then the preference is removed and the default is used.

Set the shell’s use of colors.

Default is true .

Show the last result after an execution.

Sanitize (trim-down/filter) stack traces.

Configures the editor used by the edit command.

Default is the value of the system environment variable EDITOR .

To use TextEdit, the default text editor on macOS, configure: set editor /Applications/TextEdit.app/Contents/MacOS/TextEdit

To list the current set preferences (and their values):

Limitation: At the moment, there is no way to list all the known/available preferences to be set.

User Profile Scripts and State

Profile scripts.

This script, if it exists, is loaded when the shell starts up.

This script, if it exists, is loaded when the shell enters interactive mode.

Edit-line history is stored in this file.

The register command allows you to register custom commands in the shell. For example, writing the following will register the Stats command:

where the Stats class is a class extending the org.apache.groovy.groovysh.CommandSupport class. For example:

Then the command can be called using:

Note that the command class must be found on classpath: you cannot define a new command from within the shell.

Troubleshooting

Please report any problems you run into. Please be sure to mark the JIRA issue with the Groovysh component.

Platform Problems

On Windows, JLine2 (which is used for the fancy shell input/history/completion fluff), uses a tiny DLL file to trick the evil Windows faux-shell ( CMD.EXE or COMMAND.COM ) into providing Java with unbuffered input. In some rare cases, this might fail to load or initialize.

One solution is to disable the frills and use the unsupported terminal instance. You can do that on the command-line using the --terminal flag and set it to one of:

jline.UnsupportedTerminal

Some people have issues when running groovysh with cygwin. If you have troubles, the following may help:

GMavenPlus is a Maven plugin with goals that support launching a Groovy Shell or Groovy Console bound to a Maven project.

Gradle Groovysh Plugin is a Gradle plugin that provides gradle tasks to start a Groovy Shell bound to a Gradle project.

2.4. groovyConsole, the Groovy swing console

The Groovy Swing Console allows a user to enter and run Groovy scripts. This page documents the features of this user interface.

image

Groovy Console is launched via groovyConsole or groovyConsole.bat , both located in $GROOVY_HOME/bin

The Console has an input area and an output area.

You type a Groovy script in the input area.

When you select Run from the Actions menu, the console compiles the script and runs it.

Anything that would normally be printed on System.out is printed in the output area.

If the script returns a non-null result, that result is printed.

2.4.3. Features

The Groovy Console supports several options to control classpath and other features.

There are several shortcuts that you can use to run scripts or code snippets:

Ctrl+Enter and Ctrl+R are both shortcut keys for Run Script .

If you highlight just part of the text in the input area, then Groovy runs just that text.

The result of a script is the value of the last expression executed.

You can turn the System.out capture on and off by selecting Capture System.out from the Actions menu

You can open any text file, edit it, run it (as a Groovy Script) and then save it again when you are finished.

Select File > Open (shortcut key ctrl+O ) to open a file

Select File > Save (shortcut key ctrl+S ) to save a file

Select File > New File (shortcut key ctrl+Q ) to start again with a blank input area

You can pop up a gui inspector on the last (non-null) result by selecting Inspect Last from the Actions menu. The inspector is a convenient way to view lists and maps.

The console remembers the last ten script runs. You can scroll back and forth through the history by selecting Next and Previous from the Edit menu. Ctrl-N and ctrl-P are convenient shortcut keys.

The last (non-null) result is bound to a variable named _ (an underscore).

The last result (null and non-null) for every run in the history is bound into a list variable named (two underscores). The result of the last run is [-1] , the result of the second to last run is __[-2] and so forth.

The Groovy console is a very handy tool to develop scripts. Often, you will find yourself running a script multiple times until it works the way you want it to. However, what if your code takes too long to finish or worse, creates an infinite loop? Interrupting script execution can be achieved by clicking the interrupt button on the small dialog box that pops up when a script is executing or through the interrupt icon in the toolbar.

Toolbar

However, this may not be sufficient to interrupt a script: clicking the button will interrupt the execution thread, but if your code doesn’t handle the interrupt flag, the script is likely to keep running without you being able to effectively stop it. To avoid that, you have to make sure that the Script > Allow interruption menu item is flagged. This will automatically apply an AST transformation to your script which will take care of checking the interrupt flag ( @ThreadInterrupt ). This way, you guarantee that the script can be interrupted even if you don’t explicitly handle interruption, at the cost of extra execution time.

You can change the font size by selecting Smaller Font or Larger Font from the Actions menu

The console can be run as an Applet thanks to groovy.ui.ConsoleApplet

Code is auto indented when you hit return

You can drag’n’drop a Groovy script over the text area to open a file

You can modify the classpath with which the script in the console is being run by adding a new JAR or a directory to the classpath from the Script menu

Error hyperlinking from the output area when a compilation error is expected or when an exception is thrown

To embed a Swing console in your application, simply create the Console object, load some variables, and then launch it. The console can be embedded in either Java or Groovy code. The Java code for this is:

Once the console is launched, you can use the variable values in Groovy code.

You can customize the way script output results are visualized. Let’s see how we can customize this. For example, viewing a map result would show something like this:

image

What you see here is the usual textual representation of a Map. But, what if we enabled custom visualization of certain results? The Swing console allows you to do just that. First of all, you have to ensure that the visualization option is ticked: View → Visualize Script Results — for the record, all settings of the Groovy Console are stored and remembered thanks to the Preference API. There are a few result visualizations built-in: if the script returns a java.awt.Image , a javax.swing.Icon , or a java.awt.Component with no parent, the object is displayed instead of its toString() representation. Otherwise, everything else is still just represented as text. Now, create the following Groovy script in ~/.groovy/OutputTransforms.groovy :

The Groovy Swing console will execute that script on startup, injecting a transforms list in the binding of the script, so that you can add your own script results representations. In our case, we transform the Map into a nice-looking Swing JTable. We’re now able to visualize maps in a friendly and attractive fashion, as the screenshot below shows:

image

Groovy Console can visualize the AST (Abstract Syntax Tree) representing the currently edited script, as shown by the screenshot below. This is useful when you want to understand how an AST transformation is working and particularly handy if you are developing your own AST transform. In the example below, we have annotated our class with the @Immutable annotation and the Groovy compiler has generated a lot of boilerplate code for us. We can see the code for the generated equals method in the Source tab.

AST Browser

We can even examine the JVM bytecode generated by the compiler. In the image below we are looking at the bytecode for the Groovy expression LocalDate.parse('2020/02/10', 'yyyy/MM/dd') .

AST Browser

Groovy Console can visualize the CST (Concrete Syntax Tree) representing the initial parsing of the script. This is mainly useful for parsing gurus.

CST Browser

2.5. groovydoc, the Groovy & Java documentation generator

GroovyDoc is a tool responsible for generating documentation from your code. It acts like the Javadoc tool in the Java world but is capable of handling both groovy and java files. The distribution comes with two ways of generating documentation: from command line or from Apache Ant . Other build tools like Maven or Gradle also offer wrappers for Groovydoc.

The groovydoc command line can be invoked to generate groovydocs:

where options must be picked from the following table:

Short version Long version Description

-author

Include @author paragraphs (currently not used)

-charset <charset>

Charset for cross-platform viewing of generated documentation

-classpath, -cp

--classpath

Specify where to find the class files - must be first argument

-d

--destdir <dir>

Destination directory for output files

--debug

Enable debug output

-doctitle <html>

Include title for the overview page

-exclude <pkglist>

Specify a list of packages to exclude (separated by colons for all operating systems)

-fileEncoding <charset>

Charset for generated documentation files

-footer <html>

Include footer text for each page

-header <html>

Include header text for each page

-help

--help

Display help message

-nomainforscripts

Don’t include the implicit 'public static void main' method for scripts

-noscripts

Don’t process Groovy Scripts

-notimestamp

Don’t include timestamp within hidden comment in generated HTML

-noversionstamp

Don’t include Groovy version within hidden comment in generated HTML

-overview <file>

Read overview documentation from HTML file

-package

Show package/protected/public classes and members

-private

Show all classes and members

-protected

Show protected/public classes and members (default)

-public

Show only public classes and members

-quiet

Suppress superfluous output

-sourcepath <pathlist>

Specify where to find source files (dirs separated by platform path separator)

-stylesheetfile <path>

File to change style of the generated documentation

-verbose

Enable verbose output

--version

Display the version

-windowtitle <text>

Browser window title for the documentation

2.5.2. The groovydoc Ant task

The groovydoc Ant task allows generating groovydocs from an Ant build.

Assuming all the groovy jars you need are in my.classpath (this will be groovy-VERSION.jar , groovy-ant-VERSION.jar , groovy-groovydoc-VERSION.jar plus any modules and transitive dependencies you might be using) you will need to declare this task at some point in the build.xml prior to the groovydoc task being invoked.

Attribute Description Required

destdir

Location to store the class files.

Yes

sourcepath

The sourcepath to use.

No

packagenames

Comma separated list of package files (with terminating wildcard).

No

use

Create class and package usage pages.

No

windowtitle

Browser window title for the documentation (text).

No

doctitle

Include title for the package index(first) page (html-code).

No

header

Include header text for each page (html-code).

No

footer

Include footer text for each page (html-code).

No

overview

Read overview documentation from HTML file.

No

private

Show all classes and members (i.e. including private ones) if set to ``true''.

No

<groovydoc> Nested Elements

Create link to groovydoc/javadoc output at the given URL.

Attribute Description Required

packages

Comma separated list of package prefixes

Yes

href

Base URL of external site

Yes

Custom templates

The groovydoc Ant task supports custom templates, but it requires two steps:

A custom groovydoc class

A new groovydoc task definition

The first step requires you to extend the Groovydoc class, like in the following example:

You can override the following methods:

getClassTemplates for class-level templates

getPackageTemplates for package-level templates

getDocTemplates for top-level templates

You can find the list of default templates in the org.codehaus.groovy.tools.groovydoc.gstringTemplates.GroovyDocTemplateInfo class.

Once you’ve written the class, using it is just a matter of redefining the groovydoc task:

Please note that template customization is provided as is. APIs are subject to change, so you must consider this as a fragile feature.

GMavenPlus is a Maven plugin with goals that support GroovyDoc generation.

Many IDEs and text editors support the Groovy programming language.

Editor Syntax highlighting Code completion Refactoring

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

Yes

No

No

Yes

No

No

Yes

No

No

Yes

No

No

Yes

No

No

Yes

No

No

Yes

No

3. User Guides

3.1. getting started, 3.1.1. download.

From the download page, you will be able to download the distribution (binary and source), the Windows installer (a community artifact) and the documentation for Groovy .

For a quick and effortless start on Mac OSX, Linux, WSL2 or Cygwin, you can use SDKMAN! (The Software Development Kit Manager) to download and configure any Groovy version of your choice. Basic instructions can be found below.

Download zip : Binary Release | Source Release

Download documentation : JavaDoc and zipped online documentation

Combined binary / source / documentation bundle : Distribution bundle

You can learn more about this version in the release notes or in the changelog .

If you plan on using invokedynamic support, read those notes .

For those who want to test the very latest versions of Groovy and live on the bleeding edge, you can use our snapshot builds . As soon as a build succeeds on our continuous integration server a snapshot is deployed to this repository. These snapshots are not official releases and are intended for integration testing by the development community prior to official versions being released. We welcome any feedback.

Groovy 4.0 requires Java 8+ with support for up to Java 16.

Various Groovy CI servers run the test suite (with more than 10000 tests) across numerous versions of Java. Those servers are also useful to look at to confirm supported Java versions for different Groovy releases.

If you wish to embed Groovy in your application, you may just prefer to point your build to your favourite maven repository or the Groovy artifactory instance . Please see the download page for available modules for each Groovy version.

This tool makes installing Groovy on any Bash platform (Mac OSX, Linux, Cygwin, Solaris or FreeBSD) very easy.

Simply open a new terminal and enter:

Follow the instructions on-screen to complete installation.

Open a new terminal or type the command:

Then install the latest stable Groovy:

After installation is complete and you’ve made it your default version, test it with:

That’s all there is to it!

3.1.4. Other ways to get Groovy

Installation on mac os x.

If you’re on macOS and have MacPorts installed, you can run:

If you’re on macOS and have Homebrew installed, you can run:

If you’re on Windows, you can also use the Windows installer .

You may download other distributions of Groovy from the ASF archive repository or from the Groovy artifactory instance (also includes pre-ASF versions).

If you prefer to live on the bleeding edge, you can also grab the source code from GitHub .

If you are an IDE user, you can just grab the latest IDE plugin and follow the plugin installation instructions.

These instructions describe how to install a binary distribution of Groovy :

Download a binary distribution of Groovy and unpack it into some folder on your local file system.

Set your GROOVY_HOME environment variable to the directory where you unpacked the distribution.

Add GROOVY_HOME/bin to your PATH environment variable.

Set your JAVA_HOME environment variable to point to your JDK. On OS X this is /Library/Java/Home , on other unixes its often /usr/java etc. If you’ve already installed tools like Ant or Maven you’ve probably already done this step.

You should now have Groovy installed properly. You can test this by typing the following in a command shell:

Which should create an interactive groovy shell where you can type Groovy statements. Or to run the Swing interactive console type:

To run a specific Groovy script type:

3.2. Differences with Java

Groovy tries to be as natural as possible for Java developers. We’ve tried to follow the principle of least surprise when designing Groovy, particularly for developers learning Groovy who’ve come from a Java background.

Here we list all the major differences between Java and Groovy.

All these packages and classes are imported by default, i.e. you do not have to use an explicit import statement to use them:

java.lang.*

java.util.*

groovy.lang.*

groovy.util.*

In Groovy, the methods which will be invoked are chosen at runtime. This is called runtime dispatch or multi-methods. It means that the method will be chosen based on the types of the arguments at runtime. In Java, this is the opposite: methods are chosen at compile time, based on the declared types.

The following code, written as Java code, can be compiled in both Java and Groovy, but it will behave differently:

In Java, you would have:

Whereas in Groovy:

That is because Java will use the static information type, which is that o is declared as an Object , whereas Groovy will choose at runtime, when the method is actually called. Since it is called with a String , then the String version is called.

In Java, array initializers take either of these two forms:

In Groovy, the { …​ } block is reserved for closures. That means that you cannot create array literals using Java’s array initializer shorthand syntax. You instead borrow Groovy’s literal list notation like this:

For Groovy 3+, you can optionally use the Java’s array initializer long syntax:

In Groovy, omitting a modifier on a field doesn’t result in a package-private field like in Java:

Instead, it is used to create a property , that is to say a private field , an associated getter and an associated setter .

It is possible to create a package-private field by annotating it with @PackageScope :

Java 7 introduced ARM (Automatic Resource Management) blocks (also know as try-with-resources) blocks like this:

Such blocks are supported from Groovy 3+. However, Groovy provides various methods relying on closures, which have the same effect while being more idiomatic. For example:

or, if you want a version closer to Java:

3.2.6. Inner classes

The implementation of anonymous inner classes and nested classes follow Java closely, but there are some differences, e.g. local variables accessed from within such classes don’t have to be final. We piggyback on some implementation details we use for when generating inner class bytecode.

Here’s an example of static inner class:

The usage of static inner classes is the best supported one. If you absolutely need an inner class, you should make it a static one.

In Java you can do this:

Before 3.0.0, Groovy doesn’t support the y.new X() syntax. Instead, you have to write new X(y) , like in the code below:

Caution though, Groovy supports calling methods with one parameter without giving an argument. The parameter will then have the value null. Basically the same rules apply to calling a constructor. There is a danger that you will write new X() instead of new X(this) for example. Since this might also be the regular way we have not yet found a good way to prevent this problem.
Groovy 3.0.0 supports Java style syntax for creating instances of non-static inner classes.

Java 8+ supports lambda expressions and the method reference operator ( :: ):

Groovy 3 and above also support these within the Parrot parser. In earlier versions of Groovy you should use closures instead:

As double-quoted string literals are interpreted as GString values, Groovy may fail with compile error or produce subtly different code if a class with String literal containing a dollar character is compiled with Groovy and Java compiler.

While typically, Groovy will auto-cast between GString and String if an API declares the type of a parameter, beware of Java APIs that accept an Object parameter and then check the actual type.

Singly-quoted literals in Groovy are used for String , and double-quoted result in String or GString , depending whether there is interpolation in the literal.

Groovy will automatically cast a single-character String to char only when assigning to a variable of type char . When calling methods with arguments of type char we need to either cast explicitly or make sure the value has been cast in advance.

Groovy supports two styles of casting and in the case of casting to char there are subtle differences when casting a multi-char strings. The Groovy style cast is more lenient and will take the first character, while the C-style cast will fail with exception.

In Java, == means equality of primitive types or identity for objects. In Groovy, == means equality in all places. For non-primitives, it translates to a.compareTo(b) == 0 , when evaluating equality for Comparable objects, and a.equals(b) otherwise.

To check for identity (reference equality), use the is method: a.is(b) . From Groovy 3, you can also use the === operator (or negated version): a === b (or c !== d ).

3.2.11. Primitives and wrappers

In a pure object-oriented language, everything would be an object. Java takes the stance that primitive types, such as int, boolean and double, are used very frequently and worthy of special treatment. Primitives can be efficiently stored and manipulated but can’t be used in all contexts where an object could be used. Luckily, Java auto boxes and unboxes primitives when they are passed as parameters or used as return types:

The method expects wrapper then primitive type arguments, but we are supplying parameters with a primitive then wrapper type. Similarly, the return type from is primitive, but we need the wrapper type.

Groovy does the same:

Groovy, also supports primitives and object types, however, it goes a little further in pushing OO purity; it tries hard to treat everything as an object. Any primitive typed variable or field can be treated like an object, and it will be auto-wrapped as needed. While primitive types might be used under the covers, their use should be indistinguishable from normal object use whenever possible, and they will be boxed/unboxed as needed.

Here is a little example using Java trying to (incorrectly for Java) dereference a primitive float :

The same example using Groovy compiles and runs successfully:

Because of Groovy’s additional use of un/boxing, it does not follow Java’s behavior of widening taking priority over boxing. Here’s an example using int

This is the method that Java would call, since widening has precedence over unboxing.
This is the method Groovy actually calls, since all primitive references use their wrapper class.

Since Groovy converts to wrapper classes in more places, you might wonder whether it produces less efficient bytecode for numeric expressions. Groovy has a highly optimised set of classes for doing math computations. When using @CompileStatic , expressions involving only primitives uses the same bytecode that Java would use.

Java float/double operations for both primitives and wrapper classes follow the IEEE 754 standard but there is an interesting edge case involving positive and negative zero. The standard supports distinguishing between these two cases and while in many scenarios programmers may not care about the difference, in some mathematical or data science scenarios it is important to cater for the distinction.

For primitives, Java maps down onto a special bytecode instruction when comparing such values which has the property that "Positive zero and negative zero are considered equal".

For the wrapper classes, e.g. java.base/java.lang.Float#equals(java.lang.Object) , the result is false for this same case.

Groovy on the one hand tries to follow Java behavior closely, but on the other switches automatically between primitives and wrapped equivalents in more places. To avoid confusion we recommend the following guidelines:

If you wish to distinguish between positive and negative zero, use the equals method directly or cast any primitives to their wrapper equivalent before using == .

If you wish to ignore the difference between positive and negative zero, use the equalsIgnoreZeroSign method directly or cast any non-primitives to their primitive equivalent before using == .

These guidelines are illustrated in the following example:

Recall that for non-primitives, maps to

Java does automatic widening and narrowing conversions .

Table 9. Java Conversions

'Y' indicates a conversion Java can make

'C' indicates a conversion Java can make when there is an explicit cast

'T` indicates a conversion Java can make but data is truncated

'N' indicates a conversion Java can’t make

Groovy expands greatly on this.

Table 10. Groovy Conversions

'Y' indicates a conversion Groovy can make

'D' indicates a conversion Groovy can make when compiled dynamically or explicitly cast

'T' indicates a conversion Groovy can make but data is truncated

'B' indicates a boxing/unboxing operation

'N' indicates a conversion Groovy can’t make.

The truncation uses Groovy Truth when converting to boolean / Boolean . Converting from a number to a character casts the Number.intvalue() to char . Groovy constructs BigInteger and BigDecimal using Number.doubleValue() when converting from a Float or Double , otherwise it constructs using toString() . Other conversions have their behavior defined by java.lang.Number .

Groovy has many of the same keywords as Java and Groovy 3 and above also has the same var reserved type as Java. In addition, Groovy has the following keywords:

it // within closures

Groovy is less stringent than Java in that it allows some keywords to appear in places that would be illegal in Java, e.g. the following is valid: var var = [def: 1, as: 2, in: 3, trait: 4] . Never-the-less, you are discouraged from using the above keywords in places that might cause confusion even when the compiler might be happy. In particular, avoid using them for variable, method and class names, so our previous var var example would be considered poor style.

Additional documentation is available for keywords .

3.3. Groovy Development Kit

3.3.1. working with io.

Groovy provides a number of helper methods for working with I/O. While you could use standard Java code in Groovy to deal with those, Groovy provides much more convenient ways to handle files, streams, readers, …​

In particular, you should take a look at methods added to:

the java.io.File class : http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/File.html

the java.io.InputStream class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/InputStream.html

the java.io.OutputStream class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/OutputStream.html

the java.io.Reader class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/Reader.html

the java.io.Writer class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/Writer.html

the java.nio.file.Path class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/nio/file/Path.html

The following section focuses on sample idiomatic constructs using helper methods available above but is not meant to be a complete description of all available methods. For that, please read the GDK API .

As a first example, let’s see how you would print all lines of a text file in Groovy:

The eachLine method is a method added to the File class automatically by Groovy and has many variants, for example if you need to know the line number, you can use this variant:

If for whatever reason an exception is thrown in the eachLine body, the method makes sure that the resource is properly closed. This is true for all I/O resource methods that Groovy adds.

For example in some cases you will prefer to use a Reader , but still benefit from the automatic resource management from Groovy. In the next example, the reader will be closed even if the exception occurs:

Should you need to collect the lines of a text file into a list, you can do:

Or you can even leverage the as operator to get the contents of the file into an array of lines:

How many times did you have to get the contents of a file into a byte[] and how much code does it require? Groovy makes it very easy actually:

Working with I/O is not limited to dealing with files. In fact, a lot of operations rely on input/output streams, hence why Groovy adds a lot of support methods to those, as you can see in the documentation .

As an example, you can obtain an InputStream from a File very easily:

However you can see that it requires you to deal with closing the inputstream. In Groovy it is in general a better idea to use the withInputStream idiom that will take care of that for you:

Of course in some cases you won’t want to read but write a file. One of the options is to use a Writer :

But for such a simple example, using the << operator would have been enough:

Of course we do not always deal with text contents, so you could use the Writer or directly write bytes as in this example:

Of course you can also directly deal with output streams. For example, here is how you would create an output stream to write into a file:

However you can see that it requires you to deal with closing the output stream. Again it is in general a better idea to use the withOutputStream idiom that will handle the exceptions and close the stream in any case:

In scripting contexts it is a common task to traverse a file tree in order to find some specific files and do something with them. Groovy provides multiple methods to do this. For example you can perform something on all files of a directory:

executes the closure code on each file found in the directory
executes the closure code on files in the directory matching the specified pattern

Often you will have to deal with a deeper hierarchy of files, in which case you can use eachFileRecurse :

executes the closure code on each file or directory found in the directory, recursively
executes the closure code only on files, but recursively

For more complex traversal techniques you can use the traverse method, which requires you to set a special flag indicating what to do with the traversal:

if the current file is a directory and its name is , stop the traversal
otherwise print the file name and continue

In Java it is not uncommon to serialize and deserialize data using the java.io.DataOutputStream and java.io.DataInputStream classes respectively. Groovy will make it even easier to deal with them. For example, you could serialize data into a file and deserialize it using this code:

And similarly, if the data you want to serialize implements the Serializable interface, you can proceed with an object output stream, as illustrated here:

The previous section described how easy it was to deal with files, readers or streams in Groovy. However in domains like system administration or devops it is often required to communicate with external processes.

Groovy provides a simple way to execute command line processes. Simply write the command line as a string and call the execute() method. E.g., on a *nix machine (or a Windows machine with appropriate *nix commands installed), you can execute this:

executes the command in an external process
consume the output of the command and retrieve the text

The execute() method returns a java.lang.Process instance which will subsequently allow the in/out/err streams to be processed and the exit value from the process to be inspected etc.

e.g. here is the same command as above but we will now process the resulting stream a line at a time:

executes the command in an external process
for each line of the input stream of the process
print the line

It is worth noting that in corresponds to an input stream to the standard output of the command. out will refer to a stream where you can send data to the process (its standard input).

Remember that many commands are shell built-ins and need special handling. So if you want a listing of files in a directory on a Windows machine and write:

you will receive an IOException saying  Cannot run program "dir": CreateProcess error=2, The system cannot find the file specified.

This is because dir is built-in to the Windows shell ( cmd.exe ) and can’t be run as a simple executable. Instead, you will need to write:

Also, because this functionality currently makes use of java.lang.Process undercover, the deficiencies of that class must be taken into consideration. In particular, the javadoc for this class says:

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock

Because of this, Groovy provides some additional helper methods which make stream handling for processes easier.

Here is how to gobble all of the output (including the error stream output) from your process:

There are also variations of consumeProcessOutput that make use of StringBuffer , InputStream , OutputStream etc…​ For a complete list, please read the GDK API for java.lang.Process

In addition, there is a pipeTo command (mapped to | to allow overloading) which lets the output stream of one process be fed into the input stream of another process.

Here are some examples of use:

3.3.2. Working with collections

Groovy provides native support for various collection types, including lists , maps or ranges . Most of those are based on the Java collection types and decorated with additional methods found in the Groovy development kit .

You can create lists as follows. Notice that [] is the empty list expression.

Each list expression creates an implementation of java.util.List .

Of course lists can be used as a source to construct another list:

A list is an ordered collection of objects:

Lists can be evaluated as a boolean value:

Iterating on elements of a list is usually done calling the each and eachWithIndex methods, which execute code on each item of a list:

In addition to iterating, it is often useful to create a new list by transforming each of its elements into something else. This operation, often called mapping, is done in Groovy thanks to the collect method:

Manipulating lists

The Groovy development kit contains a lot of methods on collections that enhance the standard collections with pragmatic methods, some of which are illustrated here:

And here is idiomatic Groovy code for finding the maximum and minimum in a collection:

In addition to closures, you can use a Comparator to define the comparison criteria:

We can use [] to assign a new empty list and << to append items to it:

We can add to a list in many ways:

It is however important that the + operator on a list is not mutating . Compared to << , it will create a new list, which is often not what you want and can lead to performance issues.

The Groovy development kit also contains methods allowing you to easily remove elements from a list by value:

It is also possible to remove an element by passing its index to the remove method, in which case the list is mutated:

In case you only want to remove the first element having the same value in a list, instead of removing all elements, you can call the remove method passing the value:

As you can see, there are two remove methods available. One that takes an integer and removes an element by its index, and another that will remove the first element that matches the passed value. So what should we do when we have a list of integers? In this case, you may wish to use removeAt to remove an element by its index, and removeElement to remove the first element that matches a value.

Of course, removeAt and removeElement will work with lists of any type.

Additionally, removing all the elements in a list can be done by calling the clear method:

The Groovy development kit also includes methods making it easy to reason on sets:

Working with collections often implies sorting. Groovy offers a variety of options to sort lists, from using closures to comparators, as in the following examples:

The Groovy development kit also takes advantage of operator overloading to provide methods allowing duplication of elements of a list:

In Groovy, maps (also known as associative arrays) can be created using the map literal syntax: [:] :

Map keys are strings by default: [a:1] is equivalent to ['a':1] . This can be confusing if you define a variable named a and that you want the value of a to be the key in your map. If this is the case, then you must escape the key by adding parenthesis, like in the following example:

In addition to map literals, it is possible, to get a new copy of a map, to clone it:

The resulting map is a shallow copy of the original one, as illustrated in the previous example.

Maps also act like beans so you can use the property notation to get/set items inside the Map as long as the keys are strings which are valid Groovy identifiers:

Note: by design map.foo will always look for the key foo in the map. This means foo.class will return null on a map that doesn’t contain the class key. Should you really want to know the class, then you must use getClass() :

As usual in the Groovy development kit , idiomatic iteration on maps makes use of the each and eachWithIndex methods. It’s worth noting that maps created using the map literal notation are ordered , that is to say that if you iterate on map entries, it is guaranteed that the entries will be returned in the same order they were added in the map.

Manipulating maps

Adding an element to a map can be done either using the put method, the subscript operator or using putAll :

Removing all the elements of a map can be done by calling the clear method:

Maps generated using the map literal syntax are using the object equals and hashcode methods. This means that you should never use an object which hash code is subject to change over time, or you wouldn’t be able to get the associated value back.

It is also worth noting that you should never use a GString as the key of a map, because the hash code of a GString is not the same as the hash code of an equivalent String :

We can inspect the keys, values, and entries in a view:

Mutating values returned by the view (be it a map entry, a key or a value) is highly discouraged because success of the operation directly depends on the type of the map being manipulated. In particular, Groovy relies on collections from the JDK that in general make no guarantee that a collection can safely be manipulated through keySet , entrySet , or values .

The Groovy development kit contains filtering, searching and collecting methods similar to those found for lists :

We can group a list into a map using some criteria:

Ranges allow you to create a list of sequential values. These can be used as List since Range extends java.util.List .

Ranges defined with the .. notation are inclusive (that is the list contains the from and to value).

Ranges defined with the ..< notation are half-open, they include the first value but not the last value.

Ranges defined with the <.. notation are also half-open, they include the last value but not the first value.

Ranges defined with the <..< notation are full-open, they do not include the first value nor the last value.

Note that int ranges are implemented efficiently, creating a lightweight Java object containing a from and to value.

Ranges can be used for any Java object which implements java.lang.Comparable for comparison and also have methods next() and previous() to return the next / previous item in the range. For example, you can create a range of String elements:

You can iterate on a range using a classic for loop:

but alternatively you can achieve the same effect in a more Groovy idiomatic style, by iterating a range with each method:

Ranges can be also used in the switch statement:

Syntax enhancements for collections

Thanks to the support of property notation for both lists and maps, Groovy provides syntactic sugar making it really easy to deal with nested collections, as illustrated in the following examples:

The spread operator can be used to "inline" a collection into another. It is syntactic sugar which often avoids calls to putAll and facilitates the realization of one-liners:

The "star-dot" operator is a shortcut operator allowing you to call a method or a property on all elements of a collection:

You can index into lists, arrays, maps using the subscript expression. It is interesting that strings are considered as special kinds of collections in that context:

Notice that you can use ranges to extract part of a collection:

The subscript operator can be used to update an existing collection (for collection type which are not immutable):

It is worth noting that negative indices are allowed, to extract more easily from the end of a collection:

You can use negative indices to count from the end of the List, array, String etc.

Eventually, if you use a backwards range (the starting index is greater than the end index), then the answer is reversed.

In addition to lists , maps or ranges , Groovy offers a lot of additional methods for filtering, collecting, grouping, counting, …​ which are directly available on either collections or more easily iterables.

In particular, we invite you to read the Groovy development kit API docs and specifically:

methods added to Iterable can be found here

methods added to Iterator can be found here

methods added to Collection can be found here

methods added to List can be found here

methods added to Map can be found here

3.3.3. Working with arrays

Groovy provides array support based on Java arrays with several extensions found in the Groovy development kit . The overall intention is that whether you are using an array or a collection, the code for working with the aggregate remains the same.

You can create arrays as follows. Notice that [] is also used as the empty array expression when given an explicit array type.

There are numerous other GDK methods for working with arrays. Just be a little careful to read the documentation. For collections, there are some mutating methods which alter the original collection and others which produce new collections, leaving the original untouched. Since arrays are of a fixed size, we wouldn’t expect mutating methods which altered an array’s size. Often instead, such methods return collections. Here are some interesting array GDK methods:

The groovy-dateutil module supports numerous extensions for working with Java’s classic Date and Calendar classes.

You can access the properties of a Date or Calendar using the normal array index notation with the constant field numbers from the Calendar class as shown in the following example:

Import the constants
Setting the calendar’s year, month and day of month
Accessing the calendar’s day of week

Groovy supports arithmetic on and iteration between Date and Calendar instances as shown in the following example:

You can parse strings into dates and output dates into formatted strings:

You can also create a new Date or Calendar based on an existing one:

3.3.5. Working with Date/Time types

The groovy-datetime module supports numerous extensions for working with the Date/Time API introduced in Java 8. This documentation refers to the data types defined by this API as "JSR 310 types."

A common use case when working with date/time types is to convert them to Strings (formatting) and from Strings (parsing). Groovy provides these additional formatting methods:

Method Description Example

For and , formats with

For , formats with

For , formats with and appends the short name

For , formats with

For , formats with

For , formats with and appends the short name

For and , formats with

For and , formats with formatter

For , formats with and appends the short name

For and , formats with

(with style , e.g.)

For , formats with

(with style , e.g.)

For , , and formats with

(with style , e.g.)

Formats with

(with pattern ’MM/dd/yyyy', e.g.)

For parsing, Groovy adds a static parse method to many of the JSR 310 types. The method takes two arguments: the value to be formatted and the pattern to use. The pattern is defined by the java.time.format.DateTimeFormatter API . As an example:

Note that these parse methods have a different argument ordering than the static parse method Groovy added to java.util.Date . This was done to be consistent with the existing parse methods of the Date/Time API.

Manipulating date/time

Temporal types have plus and minus methods for adding or subtracting a provided java.time.temporal.TemporalAmount argument. Because Groovy maps the + and - operators to single-argument methods of these names, a more natural expression syntax can be used to add and subtract.

Groovy provides additional plus and minus methods that accept an integer argument, enabling the above to be rewritten more succinctly:

The unit of these integers depends on the JSR 310 type operand. As evident above, integers used with ChronoLocalDate types like LocalDate have a unit of days . Integers used with Year and YearMonth have a unit of years and months , respectively. All other types have a unit of seconds , such as LocalTime , for instance:

The * operator can be used to multiply Period and Duration instances by an integer value; the / operator can be used to divide Duration instances by an integer value.

The ++ and -- operators can be used increment and decrement date/time values by one unit. Since the JSR 310 types are immutable, the operation will create a new instance with the incremented/decremented value and reassign it to the reference.

The Duration and Period types represent a negative or positive length of time. These can be negated with the unary - operator.

Interacting with date/time values

The getLong(TemporalField) method of TemporalAccessor types (e.g. LocalDate , LocalTime , ZonedDateTime , etc.) and the get(TemporalUnit) method of TemporalAmount types (namely Period and Duration ), can be invoked with Groovy’s property notation. For example:

The JSR 310 types can be used with the range operator . The following example iterates between today and the LocalDate six days from now, printing out the day of the week for each iteration. As both range bounds are inclusive, this prints all seven days of the week.

The upto method will accomplish the same as the range in the above example. The upto method iterates from the earlier start value (inclusive) to the later end value (also inclusive), calling the closure with the incremented next value once per iteration.

The downto method iterates in the opposite direction, from a later start value to an earlier end value.

The unit of iteration for upto , downto , and ranges is the same as the unit for addition and subtraction: LocalDate iterates by one day at a time, YearMonth iterates by one month, Year by one year, and everything else by one second. Both methods also support an optional a TemporalUnit argument to change the unit of iteration.

Consider the following example, where March 1st, 2018 is iterated up to March 2nd, 2018 using an iteration unit of months .

Since the start date is inclusive, the closure is called with a next date value of March 1st. The upto method then increments the date by one month, yielding the date, April 1st. Because this date is after the specified end date of March 2nd, the iteration stops immediately, having only called the closure once. This behavior is the same for the downto method except that the iteration will stop as soon as the value of next becomes earlier than the targeted end date.

In short, when iterating with the upto or downto methods with a custom unit of iteration, the current value of iteration will never exceed the end value.

The left-shift operator ( << ) can be used to combine two JSR 310 types into an aggregate type. For example, a LocalDate can be left-shifted into a LocalTime to produce a composite LocalDateTime instance.

The left-shift operator is reflexive; the order of the operands does not matter.

The right-shift operator ( >> ) produces a value representing the period or duration between the operands. For ChronoLocalDate , YearMonth , and Year , the operator yields a Period instance:

The operator produces a Duration for the time-aware JSR types:

If the value on the left-hand side of the operator is earlier than the value on the right-hand side, the result is positive. If the left-hand side is later than the right-hand side, the result is negative:

Despite the shortcomings of Date , Calendar , and TimeZone types in the java.util package they are fairly common in Java APIs (at least in those prior to Java 8). To accommodate use of such APIs, Groovy provides methods for converting between the JSR 310 types and legacy types.

Most JSR types have been fitted with toDate() and toCalendar() methods for converting to relatively equivalent java.util.Date and java.util.Calendar values. Both ZoneId and ZoneOffset have been given a toTimeZone() method for converting to java.util.TimeZone .

Note that when converting to a legacy type:

Nanosecond values are truncated to milliseconds. A LocalTime , for example, with a ChronoUnit.NANOS value of 999,999,999 nanoseconds translates to 999 milliseconds.

When converting the "local" types ( LocalDate , LocalTime , and LocalDateTime ), the time zone of the returned Date or Calendar will be the system default.

When converting a time-only type ( LocalTime or OffsetTime ), the year/month/day of the Date or Calendar is set to the current date.

When converting a date-only type ( LocalDate ), the time value of the Date or Calendar will be cleared, i.e. 00:00:00.000 .

When converting an OffsetDateTime to a Calendar , only the hours and minutes of the ZoneOffset convey into the corresponding TimeZone . Fortunately, Zone Offsets with non-zero seconds are rare.

Groovy has added a number of methods to Date and Calendar for converting into the various JSR 310 types:

3.3.6. Handy utilities

ConfigSlurper is a utility class for reading configuration files defined in the form of Groovy scripts. Like it is the case with Java *.properties files, ConfigSlurper allows a dot notation. But in addition, it allows for Closure scoped configuration values and arbitrary object types.

Usage of the dot notation
Usage of Closure scopes as an alternative to the dot notation

As can be seen in the above example, the parse method can be used to retrieve groovy.util.ConfigObject instances. The ConfigObject is a specialized java.util.Map implementation that either returns the configured value or a new ConfigObject instance but never null .

has not been specified yet it returns a when being called.

In the case of a dot being part of a configuration variable name, it can be escaped by using single or double quotes.

In addition, ConfigSlurper comes with support for environments . The environments method can be used to hand over a Closure instance that itself may consist of a several sections. Let’s say we wanted to create a particular configuration value for the development environment. When creating the ConfigSlurper instance we can use the ConfigSlurper(String) constructor to specify the target environment.

The environments aren’t restricted to any particular environment names. It solely depends on the client code what value are supported and interpreted accordingly.

The environments method is built-in but the registerConditionalBlock method can be used to register other method names in addition to the environments name.

Once the new block is registered can parse it.

For Java integration purposes the toProperties method can be used to convert the ConfigObject to a java.util.Properties object that might be stored to a *.properties text file. Be aware though that the configuration values are converted to String instances during adding them to the newly created Properties instance.

The Expando class can be used to create a dynamically expandable object. Despite its name it does not use the ExpandoMetaClass underneath. Each Expando object represents a standalone, dynamically-crafted instance that can be extended with properties (or methods) at runtime.

A special case occurs when a dynamic property registers a Closure code block. Once being registered it can be invoked as it would be done with a method call.

Groovy comes with observable lists, maps and sets. Each of these collections trigger java.beans.PropertyChangeEvent events when elements are added, removed or changed. Note that a PropertyChangeEvent is not only signalling that a certain event has occurred, moreover, it holds information on the property name and the old/new value a certain property has been changed to.

Depending on the type of change that has happened, observable collections might fire more specialized PropertyChangeEvent types. For example, adding an element to an observable list fires an ObservableList.ElementAddedEvent event.

Declares a that is capturing the fired events
and its descendant types are relevant for this listener
Registers the listener
Creates an from the given list
Triggers an event
Be aware that adding an element in fact causes two events to be triggered. The first is of type , the second is a plain that informs listeners about the change of property .

The ObservableList.ElementClearedEvent event type is another interesting one. Whenever multiple elements are removed, for example when calling clear() , it holds the elements being removed from the list.

To get an overview of all the supported event types the reader is encouraged to have a look at the JavaDoc documentation or the source code of the observable collection in use.

ObservableMap and ObservableSet come with the same concepts as we have seen for ObservableList in this section.

3.4. Metaprogramming

The Groovy language supports two flavors of metaprogramming: runtime and compile-time. The first allows altering the class model and the behavior of a program at runtime while the second only occurs at compile-time. Both have pros and cons that we will detail in this section.

3.4.1. Runtime metaprogramming

With runtime metaprogramming we can postpone to runtime the decision to intercept, inject and even synthesize methods of classes and interfaces. For a deep understanding of Groovy’s metaobject protocol (MOP) we need to understand Groovy objects and Groovy’s method handling. In Groovy we work with three kinds of objects: POJO, POGO and Groovy Interceptors. Groovy allows metaprogramming for all types of objects but in a different manner.

POJO - A regular Java object whose class can be written in Java or any other language for the JVM.

POGO - A Groovy object whose class is written in Groovy. It extends java.lang.Object and implements the groovy.lang.GroovyObject interface by default.

Groovy Interceptor - A Groovy object that implements the groovy.lang.GroovyInterceptable interface and has method-interception capability which is discussed in the GroovyInterceptable section.

For every method call Groovy checks whether the object is a POJO or a POGO. For POJOs, Groovy fetches its MetaClass from the groovy.lang.MetaClassRegistry and delegates method invocation to it. For POGOs, Groovy takes more steps, as illustrated in the following figure:

GroovyInterceptions

GroovyObject interface

groovy.lang.GroovyObject is the main interface in Groovy as the Object class is in Java. GroovyObject has a default implementation in the groovy.lang.GroovyObjectSupport class and it is responsible to transfer invocation to the groovy.lang.MetaClass object. The GroovyObject source looks like this:

This method is primarily intended to be used in conjunction with the GroovyInterceptable interface or an object’s MetaClass where it will intercept all method calls.

It is also invoked when the method called is not present on a Groovy object. Here is a simple example using an overridden invokeMethod() method:

However, the use of invokeMethod to intercept missing methods is discouraged. In cases where the intent is to only intercept method calls in the case of a failed method dispatch use methodMissing instead.

Every read access to a property can be intercepted by overriding the getProperty() method of the current object. Here is a simple example:

Forwards the request to the getter for all properties except .

You can intercept write access to properties by overriding the setProperty() method:

You can access an object’s metaClass or set your own MetaClass implementation for changing the default interception mechanism. For example, you can write your own implementation of the MetaClass interface and assign it to objects in order to change the interception mechanism:

You can find an additional example in the topic.

This functionality is related to the MetaClass implementation. In the default implementation you can access fields without invoking their getters and setters. The examples below demonstrates this approach:

Groovy supports the concept of methodMissing . This method differs from invokeMethod in that it is only invoked in the case of a failed method dispatch when no method can be found for the given name and/or the given arguments:

Typically when using methodMissing it is possible to cache the result for the next time the same method is called.

For example, consider dynamic finders in GORM. These are implemented in terms of methodMissing . The code resembles something like this:

Notice how, if we find a method to invoke, we then dynamically register a new method on the fly using ExpandoMetaClass . This is so that the next time the same method is called it is more efficient. This way of using methodMissing does not have the overhead of invokeMethod and is not expensive from the second call on.

Groovy supports the concept of propertyMissing for intercepting otherwise failing property resolution attempts. In the case of a getter method, propertyMissing takes a single String argument containing the property name:

The propertyMissing(String) method is only called when no getter method for the given property can be found by the Groovy runtime.

For setter methods a second propertyMissing definition can be added that takes an additional value argument:

As with methodMissing it is best practice to dynamically register new properties at runtime to improve the overall lookup performance.

Static variant of methodMissing method can be added via the ExpandoMetaClass or can be implemented at the class level with $static_methodMissing method.

Static variant of propertyMissing method can be added via the ExpandoMetaClass or can be implemented at the class level with $static_propertyMissing method.

The groovy.lang.GroovyInterceptable interface is marker interface that extends GroovyObject and is used to notify the Groovy runtime that all methods should be intercepted through the method dispatcher mechanism of the Groovy runtime.

When a Groovy object implements the GroovyInterceptable interface, its invokeMethod() is called for any method calls. Below you can see a simple example of an object of this type:

The next piece of code is a test which shows that both calls to existing and non-existing methods will return the same value.

We cannot use default groovy methods like because these methods are injected into all Groovy objects so they will be intercepted too.

If we want to intercept all method calls but do not want to implement the GroovyInterceptable interface we can implement invokeMethod() on an object’s MetaClass . This approach works for both POGOs and POJOs, as shown by this example:

Additional information about can be found in the section.

There are situations where it is useful if a class not under control had additional methods. In order to enable this capability, Groovy implements a feature borrowed from Objective-C, called Categories .

Categories are implemented with so-called category classes . A category class is special in that it needs to meet certain pre-defined rules for defining extension methods.

There are a few categories that are included in the system for adding functionality to classes that make them more usable within the Groovy environment:

groovy.time.TimeCategory

groovy.servlet.ServletCategory

groovy.xml.dom.DOMCategory

Category classes aren’t enabled by default. To use the methods defined in a category class it is necessary to apply the scoped use method that is provided by the GDK and available from inside every Groovy object instance:

adds methods to
adds methods to

The use method takes the category class as its first parameter and a closure code block as second parameter. Inside the Closure access to the category methods is available. As can be seen in the example above even JDK classes like java.lang.Integer or java.util.Date can be enriched with user-defined methods.

A category needs not to be directly exposed to the user code, the following will also do:

When we have a look at the groovy.time.TimeCategory class we see that the extension methods are all declared as static methods. In fact, this is one of the requirements that must be met by category classes for its methods to be successfully added to a class inside the use code block:

Another requirement is the first argument of the static method must define the type the method is attached to once being activated. The other arguments are the normal arguments the method will take as parameters.

Because of the parameter and static method convention, category method definitions may be a bit less intuitive than normal method definitions. As an alternative Groovy comes with a @Category annotation that transforms annotated classes into category classes at compile-time.

Applying the @Category annotation has the advantage of being able to use instance methods without the target type as a first parameter. The target type class is given as an argument to the annotation instead.

There is a distinct section on in the .

Metaclasses

As explained earlier, Metaclasses play a central role in method resolution. For every method invocation from groovy code, Groovy will find the MetaClass for the given object and delegate the method resolution to the metaclass via groovy.lang.MetaClass#invokeMethod(java.lang.Class,java.lang.Object,java.lang.String,java.lang.Object,boolean,boolean) which should not be confused with groovy.lang.GroovyObject#invokeMethod(java.lang.String,java.lang.Object) which happens to be a method that the metaclass may eventually call.

By default, objects get an instance of MetaClassImpl that implements the default method lookup. This method lookup includes looking up of the method in the object class ("regular" method) but also if no method is found this way it will resort to calling methodMissing and ultimately groovy.lang.GroovyObject#invokeMethod(java.lang.String,java.lang.Object)

Custom metaclasses

You can change the metaclass of any object or class and replace it with a custom implementation of the MetaClass groovy.lang.MetaClass . Usually you will want to extend one of the existing metaclasses such as MetaClassImpl , DelegatingMetaClass , ExpandoMetaClass , or ProxyMetaClass ; otherwise you will need to implement the complete method lookup logic. Before using a new metaclass instance you should call groovy.lang.MetaClass#initialize() , otherwise the metaclass may or may not behave as expected.

If you only need to decorate an existing metaclass the DelegatingMetaClass simplifies that use case. The old metaclass implementation is still accessible via super making it easy to apply pretransformations to the inputs, routing to other methods and postprocessing the outputs.

It is possible to change the metaclass at startup time by giving the metaclass a specially crafted (magic) class name and package name. In order to change the metaclass for java.lang.Integer it’s enough to put a class groovy.runtime.metaclass.java.lang.IntegerMetaClass in the classpath. This is useful, for example, when working with frameworks if you want to do metaclass changes before your code is executed by the framework. The general form of the magic package is groovy.runtime.metaclass.[package].[class]MetaClass . In the example below the [package] is java.lang and the [class] is Integer :

By compiling the above file with groovyc IntegerMetaClass.groovy a ./groovy/runtime/metaclass/java/lang/IntegerMetaClass.class will be generated. The example below will use this new metaclass:

By running that file with groovy -cp . testInteger.groovy the IntegerMetaClass will be in the classpath and therefore it will become the metaclass for java.lang.Integer intercepting the method calls to isBiggerThan*() methods.

You can change the metaclass of individual objects separately, so it’s possible to have multiple object of the same class with different metaclasses.

ExpandoMetaClass

Groovy comes with a special MetaClass the so-called ExpandoMetaClass . It is special in that it allows for dynamically adding or changing methods, constructors, properties and even static methods by using a neat closure syntax.

Applying those modifications can be especially useful in mocking or stubbing scenarios as shown in the Testing Guide .

Every java.lang.Class is supplied by Groovy with a special metaClass property that will give you a reference to an ExpandoMetaClass instance. This instance can then be used to add methods or change the behaviour of already existing ones.

By default doesn’t do inheritance. To enable this you must call before your app starts such as in the main method or servlet bootstrap.

The following sections go into detail on how ExpandoMetaClass can be used in various scenarios.

Once the ExpandoMetaClass is accessed by calling the metaClass property, methods can be added by using either the left shift << or the = operator.

Note that the left shift operator is used to a new method. If a public method with the same name and parameter types is declared by the class or interface, including those inherited from superclasses and superinterfaces but excluding those added to the at runtime, an exception will be thrown. If you want to a method declared by the class or interface you can use the operator.

The operators are applied on a non-existent property of metaClass passing an instance of a Closure code block.

The example above shows how a new method can be added to a class by accessing the metaClass property and using the << or = operator to assign a Closure code block. The Closure parameters are interpreted as method parameters. Parameterless methods can be added by using the {→ …​} syntax.

ExpandoMetaClass supports two mechanisms for adding or overriding properties.

Firstly, it has support for declaring a mutable property by simply assigning a value to a property of metaClass :

Another way is to add getter and/or setter methods by using the standard mechanisms for adding instance methods.

In the source code example above the property is dictated by the closure and is a read-only property. It is feasible to add an equivalent setter method but then the property value needs to be stored for later usage. This could be done as shown in the following example.

This is not the only technique however. For example in a servlet container one way might be to store the values in the currently executing request as request attributes (as is done in some cases in Grails).

Constructors can be added by using a special constructor property. Either the << or = operator can be used to assign a Closure code block. The Closure arguments will become the constructor arguments when the code is executed at runtime.

Be careful when adding constructors however, as it is very easy to get into stack overflow troubles.

Static methods can be added using the same technique as instance methods with the addition of the static qualifier before the method name.

With ExpandoMetaClass it is possible to use Groovy’s method pointer syntax to borrow methods from other classes.

Since Groovy allows you to use Strings as property names this in turns allows you to dynamically create method and property names at runtime. To create a method with a dynamic name simply use the language feature of reference property names as strings.

The same concept can be applied to static methods and properties.

One application of dynamic method names can be found in the Grails web application framework. The concept of "dynamic codecs" is implemented by using dynamic method names.

The example above shows a codec implementation. Grails comes with various codec implementations each defined in a single class. At runtime there will be multiple codec classes in the application classpath. At application startup the framework adds a encodeXXX and a decodeXXX method to certain metaclasses where XXX is the first part of the codec class name (e.g. encodeHTML ). This mechanism is in the following shown in some Groovy pseudocode:

At runtime it is often useful to know what other methods or properties exist at the time the method is executed. ExpandoMetaClass provides the following methods as of this writing:

getMetaMethod

hasMetaMethod

getMetaProperty

hasMetaProperty

Why can’t you just use reflection? Well because Groovy is different, it has the methods that are "real" methods and methods that are available only at runtime. These are sometimes (but not always) represented as MetaMethods. The MetaMethods tell you what methods are available at runtime, thus your code can adapt.

This is of particular use when overriding invokeMethod , getProperty and/or setProperty .

Another feature of ExpandoMetaClass is that it allows to override the methods invokeMethod , getProperty and setProperty , all of them can be found in the groovy.lang.GroovyObject class.

The following example shows how to override invokeMethod :

The first step in the Closure code is to look up the MetaMethod for the given name and arguments. If the method can be found everything is fine and it is delegated to. If not, a dummy value is returned.

A is a method that is known to exist on the whether added at runtime or at compile-time.

The same logic can be used to override setProperty or getProperty .

The important thing to note here is that instead of a MetaMethod a MetaProperty instance is looked up. If that exists the getProperty method of the MetaProperty is called, passing the delegate.

ExpandoMetaClass even allows for overriding static method with a special invokeMethod syntax.

The logic that is used for overriding the static method is the same as we’ve seen before for overriding instance methods. The only difference is the access to the metaClass.static property and the call to getStaticMethodName for retrieving the static MetaMethod instance.

It is possible to add methods onto interfaces with ExpandoMetaClass . To do this however, it must be enabled globally using the ExpandoMetaClass.enableGlobally() method before application start-up.

Extension modules

An extension module allows you to add new methods to existing classes, including classes which are precompiled, like classes from the JDK. Those new methods, unlike those defined through a metaclass or using a category, are available globally. For example, when you write:

The getText method doesn’t exist on the File class. However, Groovy knows it because it is defined in a special class, ResourceGroovyMethods :

You may notice that the extension method is defined using a static method in a helper class (where various extension methods are defined). The first argument of the getText method corresponds to the receiver, while additional parameters correspond to the arguments of the extension method. So here, we are defining a method called getText on the File class (because the first argument is of type File ), which takes a single argument as a parameter (the encoding String ).

The process of creating an extension module is simple:

write an extension class like above

write a module descriptor file

Then you have to make the extension module visible to Groovy, which is as simple as having the extension module classes and descriptor available on classpath. This means that you have the choice:

either provide the classes and module descriptor directly on classpath

or bundle your extension module into a jar for reusability

An extension module may add two kind of methods to a class:

instance methods (to be called on an instance of a class)

static methods (to be called on the class itself)

To add an instance method to an existing class, you need to create an extension class. For example, let’s say you want to add a maxRetries method on Integer which accepts a closure and executes it at most n times until no exception is thrown. To do that, you only need to write the following:

The extension class
First argument of the static method corresponds to the receiver of the message, that is to say the extended instance

Then, after having declared your extension class , you can call it this way:

It is also possible to add static methods to a class. In that case, the static method needs to be defined in its own file. Static and instance extension methods cannot be present in the same class.

The static extension class
First argument of the static method corresponds to the class being extended and is

In which case you can call it directly on the String class:

For Groovy to be able to load your extension methods, you must declare your extension helper classes. You must create a file named org.codehaus.groovy.runtime.ExtensionModule into the META-INF/groovy directory:

The module descriptor requires 4 keys:

moduleName : the name of your module

moduleVersion : the version of your module. Note that version number is only used to check that you don’t load the same module in two different versions.

extensionClasses : the list of extension helper classes for instance methods. You can provide several classes, given that they are comma separated.

staticExtensionClasses : the list of extension helper classes for static methods. You can provide several classes, given that they are comma separated.

Note that it is not required for a module to define both static helpers and instance helpers, and that you may add several classes to a single module. You can also extend different classes in a single module without problem. It is even possible to use different classes in a single extension class, but it is recommended to group extension methods into classes by feature set.

It’s worth noting that you can’t use an extension which is compiled at the same time as code using it. That means that to use an extension, it has to be available on classpath, as compiled classes, before the code using it gets compiled. Usually, this means that you can’t have the test classes in the same source unit as the extension class itself. Since in general, test sources are separated from normal sources and executed in another step of the build, this is not an issue.

Unlike categories, extension modules are compatible with type checking: if they are found on classpath, then the type checker is aware of the extension methods and will not complain when you call them. It is also compatible with static compilation.

3.4.2. Compile-time metaprogramming

Compile-time metaprogramming in Groovy allows code generation at compile-time. Those transformations are altering the Abstract Syntax Tree (AST) of a program, which is why in Groovy we call it AST transformations. AST transformations allow you to hook into the compilation process, modify the AST and continue the compilation process to generate regular bytecode. Compared to runtime metaprogramming, this has the advantage of making the changes visible in the class file itself (that is to say, in the bytecode). Making it visible in the bytecode is important for example if you want the transformations to be part of the class contract (implementing interfaces, extending abstract classes, …​) or even if you need your class to be callable from Java (or other JVM languages). For example, an AST transformation can add methods to a class. If you do it with runtime metaprogramming, the new method would only be visible from Groovy. If you do the same using compile-time metaprogramming, the method would be visible from Java too. Last but not least, performance would likely be better with compile-time metaprogramming (because no initialization phase is required).

In this section, we will start with explaining the various compile-time transformations that are bundled with the Groovy distribution. In a subsequent section, we will describe how you can implement your own AST transformations and what are the disadvantages of this technique.

Available AST transformations

Groovy comes with various AST transformations covering different needs: reducing boilerplate (code generation), implementing design patterns (delegation, …​), logging, declarative concurrency, cloning, safer scripting, tweaking the compilation, implementing Swing patterns, testing and eventually managing dependencies. If none of those AST transformations cover your needs, you can still implement your own, as show in section Developing your own AST transformations .

AST transformations can be separated into two categories:

global AST transformations are applied transparently, globally, as soon as they are found on compile classpath

local AST transformations are applied by annotating the source code with markers. Unlike global AST transformations, local AST transformations may support parameters.

Groovy doesn’t ship with any global AST transformation, but you can find a list of local AST transformations available for you to use in your code here:

Code generation transformations

This category of transformation includes AST transformations which help removing boilerplate code. This is typically code that you have to write but that does not carry any useful information. By autogenerating this boilerplate code, the code you have to write is left clean and concise and the chance of introducing an error by getting such boilerplate code incorrect is reduced.

The @ToString AST transformation generates a human-readable toString representation of the class. For example, annotating the Person class like below will automatically generate the toString method for you:

With this definition, then the following assertion passes, meaning that a toString method taking the field values from the class and printing them out has been generated:

The @ToString annotation accepts several parameters which are summarized in the following table:

Attribute Default value Description Example

excludes

Empty list

List of properties to exclude from toString

includes

Undefined marker list (indicates all fields)

List of fields to include in toString

includeSuper

False

Should superclass be included in toString

includeNames

false

Whether to include names of properties in generated toString.

includeFields

False

Should fields be included in toString, in addition to properties

includeSuperProperties

False

Should super properties be included in toString

includeSuperFields

False

Should visible super fields be included in toString

ignoreNulls

False

Should properties/fields with null value be displayed

includePackage

True

Use fully qualified class name instead of simple name in toString

allProperties

True

Include all JavaBean properties in toString

cache

False

Cache the toString string. Should only be set to true if the class is immutable.

allNames

False

Should fields and/or properties with internal names be included in the generated toString

The @EqualsAndHashCode AST transformation aims at generating equals and hashCode methods for you. The generated hashcode follows the best practices as described in Effective Java by Josh Bloch :

There are several options available to tweak the behavior of @EqualsAndHashCode :

Attribute Default value Description Example

excludes

Empty list

List of properties to exclude from equals/hashCode

includes

Undefined marker list (indicating all fields)

List of fields to include in equals/hashCode

cache

False

Cache the hashCode computation. Should only be set to true if the class is immutable.

callSuper

False

Whether to include super in equals and hashCode calculations

includeFields

False

Should fields be included in equals/hashCode, in addition to properties

useCanEqual

True

Should equals call canEqual helper method.

allProperties

False

Should JavaBean properties be included in equals and hashCode calculations

allNames

False

Should fields and/or properties with internal names be included in equals and hashCode calculations

The @TupleConstructor annotation aims at eliminating boilerplate code by generating constructors for you. A tuple constructor is created having a parameter for each property (and possibly each field). Each parameter has a default value (using the initial value of the property if present or otherwise Java’s default value according to the properties type).

Normally you don’t need to understand the implementation details of the generated constructor(s); you just use them in the normal way. However, if you want to add multiple constructors, understand Java integration options or meet requirements of some dependency injection frameworks, then some details are useful.

As previously mentioned, the generated constructor has default values applied. In later compilation phases, the Groovy compiler’s standard default value processing behavior is then applied. The end result is that multiple constructors are placed within the bytecode of your class. This provides a well understood semantics and is also useful for Java integration purposes. As an example, the following code will generate 3 constructors:

The first constructor is a no-arg constructor which allows the traditional map-style construction so long as you don’t have final properties. Groovy calls the no-arg constructor and then the relevant setters under the covers. It is worth noting that if the first property (or field) has type LinkedHashMap or if there is a single Map, AbstractMap or HashMap property (or field), then the map-style named arguments won’t be available.

The other constructors are generated by taking the properties in the order they are defined. Groovy will generate as many constructors as there are properties (or fields, depending on the options).

Setting the defaults attribute (see the available configuration options table) to false , disables the normal default values behavior which means:

Exactly one constructor will be produced

Attempting to use an initial value will produce an error

Map-style named arguments won’t be available

This attribute is normally only used in situations where another Java framework is expecting exactly one constructor, e.g. injection frameworks or JUnit parameterized runners.

If the @PropertyOptions annotation is also found on the class with the @TupleConstructor annotation, then the generated constructor may contain custom property handling logic. The propertyHandler attribute on the @PropertyOptions annotation could for instance be set to ImmutablePropertyHandler which will result in the addition of the necessary logic for immutable classes (defensive copy in, cloning, etc.). This normally would happen automatically behind the scenes when you use the @Immutable meta-annotation. Some of the annotation attributes might not be supported by all property handlers.

The @TupleConstructor AST transformation accepts several annotation attributes:

Attribute Default value Description Example

excludes

Empty list

List of properties to exclude from tuple constructor generation

includes

Undefined list (indicates all fields)

List of fields to include in tuple constructor generation

includeProperties

True

Should properties be included in tuple constructor generation

includeFields

False

Should fields be included in tuple constructor generation, in addition to properties

includeSuperProperties

True

Should properties from super classes be included in tuple constructor generation

includeSuperFields

False

Should fields from super classes be included in tuple constructor generation

callSuper

False

Should super properties be called within a call to the parent constructor rather than set as properties

force

False

By default, the transformation will do nothing if a constructor is already defined. Setting this attribute to true, the constructor will be generated and it’s your responsibility to ensure that no duplicate constructor is defined.

defaults

True

Indicates that default value processing is enabled for constructor parameters. Set to false to obtain exactly one constructor but with initial value support and named-arguments disabled.

useSetters

False

By default, the transformation will directly set the backing field of each property from its corresponding constructor parameter. Setting this attribute to true, the constructor will instead call setters if they exist. It’s usually deemed bad style from within a constructor to call setters that can be overridden. It’s your responsibility to avoid such bad style.

allNames

False

Should fields and/or properties with internal names be included within the constructor

allProperties

False

Should JavaBean properties be included within the constructor

pre

empty

A closure containing statements to be inserted at the start of the generated constructor(s)

post

empty

A closure containing statements to be inserted at the end of the generated constructor(s)

Setting the defaults annotation attribute to false and the force annotation attribute to true allows multiple tuple constructors to be created by using different customization options for the different cases (provided each case has a different type signature) as shown in the following example:

Similarly, here is another example using different options for includes :

The @MapConstructor annotation aims at eliminating boilerplate code by generating a map constructor for you. A map constructor is created such that each property in the class is set based on the value in the supplied map having the key with the name of the property. Usage is as shown in this example:

The generated constructor will be roughly like this:

The @Canonical meta-annotation combines the @ToString , @EqualsAndHashCode and @TupleConstructor annotations:

A similar immutable class can be generated using the @Immutable meta-annotation instead. The @Canonical meta-annotation supports the configuration options found in the annotations it aggregates. See those annotations for more details.

The @Canonical meta-annotation can be used in conjunction with an explicit use one or more of its component annotations, like this:

Any applicable annotation attributes from @Canonical are passed along to the explicit annotation but attributes already existing in the explicit annotation take precedence.

The @InheritConstructor AST transformation aims at generating constructors matching super constructors for you. This is in particular useful when overriding exception classes:

The @InheritConstructor AST transformation supports the following configuration options:

Attribute Default value Description Example

constructorAnnotations

False

Whether to carry over annotations from the constructor during copying

parameterAnnotations

False

Whether to carry over annotations from the constructor parameters when copying the constructor

The @Category AST transformation simplifies the creation of Groovy categories. Historically, a Groovy category was written like this:

The @Category transformation lets you write the same using an instance-style class, rather than a static class style. This removes the need for having the first argument of each method being the receiver. The category can be written like this:

Note that the mixed in class can be referenced using this instead. It’s also worth noting that using instance fields in a category class is inherently unsafe: categories are not stateful (like traits).

The @IndexedProperty annotation aims at generating indexed getters/setters for properties of list/array types. This is in particular useful if you want to use a Groovy class from Java. While Groovy supports GPath to access properties, this is not available from Java. The @IndexedProperty annotation will generate indexed properties of the following form:

The @Lazy AST transformation implements lazy initialization of fields. For example, the following code:

will produce the following code:

The default value which is used to initialize the field is the default constructor of the declaration type. It is possible to define a default value by using a closure on the right hand side of the property assignment, as in the following example:

In that case, the generated code looks like the following:

If the field is declared volatile then initialization will be synchronized using the double-checked locking pattern.

Using the soft=true parameter, the helper field will use a SoftReference instead, providing a simple way to implement caching. In that case, if the garbage collector decides to collect the reference, initialization will occur the next time the field is accessed.

The @Newify AST transformation is used to bring alternative syntaxes to construct objects:

Using the Python style:

or using the Ruby style:

The Ruby version can be disabled by setting the auto flag to false .

The @Sortable AST transformation is used to help write classes that are Comparable and easily sorted typically by numerous properties. It is easy to use as shown in the following example where we annotate the Person class:

The generated class has the following properties:

it implements the Comparable interface

it contains a compareTo method with an implementation based on the natural ordering of the first , last and born properties

it has three methods returning comparators: comparatorByFirst , comparatorByLast and comparatorByBorn .

The generated compareTo method will look like this:

As an example of the generated comparators, the comparatorByFirst comparator will have a compare method that looks like this:

The Person class can be used wherever a Comparable is expected and the generated comparators wherever a Comparator is expected as shown by these examples:

Normally, all properties are used in the generated compareTo method in the priority order in which they are defined. You can include or exclude certain properties from the generated compareTo method by giving a list of property names in the includes or excludes annotation attributes. If using includes , the order of the property names given will determine the priority of properties when comparing. To illustrate, consider the following Person class definition:

It will have two comparator methods comparatorByFirst and comparatorByBorn and the generated compareTo method will look like this:

This Person class can be used as follows:

The behavior of the @Sortable AST transformation can be further changed using the following additional parameters:

Attribute Default value Description Example

allProperties

True

Should JavaBean properties (ordered after native properties) be used

allNames

False

Should properties with "internal" names be used

includeSuperProperties

False

Should super properties also be used (ordered first)

The @Builder AST transformation is used to help write classes that can be created using fluent api calls. The transform supports multiple building strategies to cover a range of cases and there are a number of configuration options to customize the building process. If you’re an AST hacker, you can also define your own strategy class. The following table lists the available strategies that are bundled with Groovy and the configuration options each strategy supports.

Strategy

Description

builderClassName

builderMethodName

buildMethodName

prefix

includes/excludes

includeSuperProperties

allNames

chained setters

n/a

n/a

n/a

yes, default "set"

yes

n/a

yes, default

explicit builder class, class being built untouched

n/a

n/a

yes, default "build"

yes, default ""

yes

yes, default

yes, default

creates a nested helper class

yes, default Builder

yes, default "builder"

yes, default "build"

yes, default ""

yes

yes, default

yes, default

creates a nested helper class providing type-safe fluent creation

yes, default Initializer

yes, default "createInitializer"

yes, default "create" but usually only used internally

yes, default ""

yes

yes, default

yes, default

To use the SimpleStrategy , annotate your Groovy class using the @Builder annotation, and specify the strategy as shown in this example:

Then, just call the setters in a chained fashion as shown here:

For each property, a generated setter will be created which looks like this:

You can specify a prefix as shown in this example:

And calling the chained setters would look like this:

You can use the SimpleStrategy in conjunction with @TupleConstructor . If your @Builder annotation doesn’t have explicit includes or excludes annotation attributes but your @TupleConstructor annotation does, the ones from @TupleConstructor will be re-used for @Builder . The same applies for any annotation aliases which combine @TupleConstructor such as @Canonical .

The annotation attribute useSetters can be used if you have a setter which you want called as part of the construction process. See the JavaDoc for details.

The annotation attributes builderClassName , buildMethodName , builderMethodName , forClass and includeSuperProperties are not supported for this strategy.

Groovy already has built-in building mechanisms. Don’t rush to using if the built-in mechanisms meet your needs. Some examples:

To use the ExternalStrategy , create and annotate a Groovy builder class using the @Builder annotation, specify the class the builder is for using forClass and indicate use of the ExternalStrategy . Suppose you have the following class you would like a builder for:

you explicitly create and use your builder class as follows:

Note that the (normally empty) builder class you provide will be filled in with appropriate setters and a build method. The generated build method will look something like:

The class you are creating the builder for can be any Java or Groovy class following the normal JavaBean conventions, e.g. a no-arg constructor and setters for the properties. Here is an example using a Java class:

The generated builder can be customised using the prefix , includes , excludes and buildMethodName annotation attributes. Here is an example illustrating various customisations:

The builderMethodName and builderClassName annotation attributes for @Builder aren’t applicable for this strategy.

You can use the ExternalStrategy in conjunction with @TupleConstructor . If your @Builder annotation doesn’t have explicit includes or excludes annotation attributes but the @TupleConstructor annotation of the class you are creating the builder for does, the ones from @TupleConstructor will be re-used for @Builder . The same applies for any annotation aliases which combine @TupleConstructor such as @Canonical .

To use the DefaultStrategy , annotate your Groovy class using the @Builder annotation as shown in this example:

If you want, you can customize various aspects of the building process using the builderClassName , buildMethodName , builderMethodName , prefix , includes and excludes annotation attributes, some of which are used in the example here:

This strategy also supports annotating static methods and constructors. In this case, the static method or constructor parameters become the properties to use for building purposes and in the case of static methods, the return type of the method becomes the target class being built. If you have more than one @Builder annotation used within a class (at either the class, method or constructor positions) then it is up to you to ensure that the generated helper classes and factory methods have unique names (i.e. no more than one can use the default name values). Here is an example highlighting method and constructor usage (and also illustrating the renaming required for unique names).

The forClass annotation attribute is not supported for this strategy.

To use the InitializerStrategy , annotate your Groovy class using the @Builder annotation, and specify the strategy as shown in this example:

Your class will be locked down to have a single public constructor taking a "fully set" initializer. It will also have a factory method to create the initializer. These are used as follows:

Any attempt to use the initializer which doesn’t involve setting all the properties (though order is not important) will result in a compilation error. If you don’t need this level of strictness, you don’t need to use @CompileStatic .

You can use the InitializerStrategy in conjunction with @Canonical and @Immutable . If your @Builder annotation doesn’t have explicit includes or excludes annotation attributes but your @Canonical annotation does, the ones from @Canonical will be re-used for @Builder . Here is an example using @Builder with @Immutable :

This strategy also supports annotating static methods and constructors. In this case, the static method or constructor parameters become the properties to use for building purposes and in the case of static methods, the return type of the method becomes the target class being built. If you have more than one @Builder annotation used within a class (at either the class, method or constructor positions) then it is up to you to ensure that the generated helper classes and factory methods have unique names (i.e. no more than one can use the default name values). For an example of method and constructor usage but using the DefaultStrategy strategy, consult that strategy’s documentation.

The annotation attribute forClass is not supported for this strategy.

The @AutoImplement AST transformation supplies dummy implementations for any found abstract methods from superclasses or interfaces. The dummy implementation is the same for all abstract methods found and can be:

essentially empty (exactly true for void methods and for methods with a return type, returns the default value for that type)

a statement that throws a specified exception (with optional message)

some user supplied code

The first example illustrates the default case. Our class is annotated with @AutoImplement , has a superclass and a single interface as can be seen here:

A void close() method from the Closeable interface is supplied and left empty. Implementations are also supplied for the three abstract methods from the super class. The get , addAll and size methods have return types of String , boolean and int respectively with default values null , false and 0 . We can use our class (and check the expected return type for one of the methods) using the following code:

It is also worthwhile examining the equivalent generated code:

The second example illustrates the simplest exception case. Our class is annotated with @AutoImplement , has a superclass and an annotation attribute indicates that an IOException should be thrown if any of our "dummy" methods are called. Here is the class definition:

We can use the class (and check the expected exception is thrown for one of the methods) using the following code:

It is also worthwhile examining the equivalent generated code where three void methods have been provided all of which throw the supplied exception:

The third example illustrates the exception case with a supplied message. Our class is annotated with @AutoImplement , implements an interface, and has annotation attributes to indicate that an UnsupportedOperationException with Not supported by MyIterator as the message should be thrown for any supplied methods. Here is the class definition:

We can use the class (and check the expected exception is thrown and has the correct message for one of the methods) using the following code:

The fourth example illustrates the case of user supplied code. Our class is annotated with @AutoImplement , implements an interface, has an explicitly overridden hasNext method, and has an annotation attribute containing the supplied code for any supplied methods. Here is the class definition:

We can use the class (and check the expected exception is thrown and has a message of the expected form) using the following code:

It is also worthwhile examining the equivalent generated code where the next method has been supplied:

The @NullCheck AST transformation adds null-check guard statements to constructors and methods which cause those methods to fail early when supplied with null arguments. It can be seen as a form of defensive programming. The annotation can be added to individual methods or constructors, or to the class in which case it will apply to all methods/constructors.

Class design annotations

This category of annotations are aimed at simplifying the implementation of well-known design patterns (delegation, singleton, …​) by using a declarative style.

@BaseScript is used within scripts to indicate that the script should extend from a custom script base class rather than groovy.lang.Script . See the documentation for domain specific languages for further details.

The @Delegate AST transformation aims at implementing the delegation design pattern. In the following class:

The when property is annotated with @Delegate , meaning that the Event class will delegate calls to Date methods to the when property. In this case, the generated code looks like this:

Then you can call the before method, for example, directly on the Event class:

Instead of annotating a property (or field), you can also annotate a method. In this case, the method can be thought of as a getter or factory method for the delegate. As an example, here is a class which (rather unusually) has a pool of delegates which are accessed in a round-robin fashion:

Here is an example usage of that class:

Using a standard list in this round-robin fashion would violate many expected properties of lists, so don’t expect the above class to do anything useful beyond this trivial example.

The behavior of the @Delegate AST transformation can be changed using the following parameters:

Attribute Default value Description Example

interfaces

True

Should the interfaces implemented by the field be implemented by the class too

deprecated

false

If true, also delegates methods annotated with @Deprecated

methodAnnotations

False

Whether to carry over annotations from the methods of the delegate to your delegating method.

parameterAnnotations

False

Whether to carry over annotations from the method parameters of the delegate to your delegating method.

excludes

Empty array

A list of methods to be excluded from delegation. For more fine-grained control, see also .

includes

Undefined marker array (indicates all methods)

A list of methods to be included in delegation. For more fine-grained control, see also .

excludeTypes

Empty array

A list of interfaces containing method signatures to be excluded from delegation

includeTypes

Undefined marker array (indicates no list be default)

A list of interfaces containing method signatures to be included in delegation

allNames

False

Should the delegate pattern be also applied to methods with internal names

The @Immutable meta-annotation combines the following annotations:

@EqualsAndHashCode

@TupleConstructor

@MapConstructor

@ImmutableBase

@ImmutableOptions

@PropertyOptions

@KnownImmutable

The @Immutable meta-annotation simplifies the creation of immutable classes. Immutable classes are useful since they are often easier to reason about and are inherently thread-safe. See Effective Java, Minimize Mutability for all the details about how to achieve immutable classes in Java. The @Immutable meta-annotation does most of the things described in Effective Java for you automatically. To use the meta-annotation, all you have to do is annotate the class like in the following example:

One of the requirements for immutable classes is that there is no way to modify any state information within the class. One requirement to achieve this is to use immutable classes for each property or alternatively perform special coding such as defensive copy in and defensive copy out for any mutable properties within the constructors and property getters. Between @ImmutableBase , @MapConstructor and @TupleConstructor properties are either identified as immutable or the special coding for numerous known cases is handled automatically. Various mechanisms are provided for you to extend the handled property types which are allowed. See @ImmutableOptions and @KnownImmutable for details.

The results of applying @Immutable to a class are pretty similar to those of applying the @Canonical meta-annotation but the generated class will have extra logic to handle immutability. You will observe this by, for instance, trying to modify a property which will result in a ReadOnlyPropertyException being thrown since the backing field for the property will have been automatically made final.

The @Immutable meta-annotation supports the configuration options found in the annotations it aggregates. See those annotations for more details.

Immutable classes generated with @ImmutableBase are automatically made final. Also, the type of each property is checked and various checks are made on the class, for example, public instance fields currently aren’t allowed. It also generates a copyWith constructor if desired.

The following annotation attribute is supported:

Attribute Default value Description Example

copyWith

false

A boolean whether to generate a method.

This annotation allows you to specify a custom property handler to be used by transformations during class construction. It is ignored by the main Groovy compiler but is referenced by other transformations like @TupleConstructor , @MapConstructor , and @ImmutableBase . It is frequently used behind the scenes by the @Immutable meta-annotation.

This annotation allows you to specify a custom visibility for a construct generated by another transformation. It is ignored by the main Groovy compiler but is referenced by other transformations like @TupleConstructor , @MapConstructor , and @NamedVariant .

Groovy’s immutability support relies on a predefined list of known immutable classes (like java.net.URI or java.lang.String and fails if you use a type which is not in that list, you are allowed to add to the list of known immutable types thanks to the following annotation attributes of the @ImmutableOptions annotation:

Attribute Default value Description Example

knownImmutableClasses

Empty list

A list of classes which are deemed immutable.

knownImmutables

Empty list

A list of property names which are deemed immutable.

If you deem a type as immutable and it isn’t one of the ones automatically handled, then it is up to you to correctly code that class to ensure immutability.

The @KnownImmutable annotation isn’t actually one that triggers any AST transformations. It is simply a marker annotation. You can annotate your classes with the annotation (including Java classes) and they will be recognized as acceptable types for members within an immutable class. This saves you having to explicitly use the knownImmutables or knownImmutableClasses annotation attributes from @ImmutableOptions .

The @Memoized AST transformations simplifies the implementation of caching by allowing the result of method calls to be cached just by annotating the method with @Memoized . Let’s imagine the following method:

This emulates a long computation, based on the actual parameters of the method. Without @Memoized , each method call would take several seconds plus it would return a random result:

Adding @Memoized changes the semantics of the method by adding caching, based on the parameters:

The size of the cache can be configured using two optional parameters:

protectedCacheSize : the number of results which are guaranteed not to be cleared after garbage collection

maxCacheSize : the maximum number of results that can be kept in memory

By default, the size of the cache is unlimited and no cache result is protected from garbage collection. Setting a protectedCacheSize>0 would create an unlimited cache with some results protected. Setting maxCacheSize>0 would create a limited cache but without any protection from garbage protection. Setting both would create a limited, protected cache.

The @TailRecursive annotation can be used to automatically transform a recursive call at the end of a method into an equivalent iterative version of the same code. This avoids stack overflow due to too many recursive calls. Below is an example of use when calculating factorial:

Currently, the annotation will only work for self-recursive method calls, i.e. a single recursive call to the exact same method again. Consider using Closures and trampoline() if you have a scenario involving simple mutual recursion. Also note that only non-void methods are currently handled (void calls will result in a compilation error).

Currently, some forms of method overloading can trick the compiler, and some non-tail recursive calls are erroneously treated as tail recursive.

The @Singleton annotation can be used to implement the singleton design pattern on a class. The singleton instance is defined eagerly by default, using class initialization, or lazily, in which case the field is initialized using double-checked locking.

By default, the singleton is created eagerly when the class is initialized and available through the instance property. It is possible to change the name of the singleton using the property parameter:

And it is also possible to make initialization lazy using the lazy parameter:

In this example, we also set the strict parameter to false, which allows us to define our own constructor.

Deprecated. Consider using traits instead.

Logging improvements

Groovy provides a family of AST transformations that help with integration of the most widely used logging frameworks. There is a transform and associated annotation for each of the common frameworks. These transforms provide a streamlined declarative approach to using the logging framework. In each case, the transform will:

add a static final log field to the annotated class corresponding to the logger

wrap all calls to log.level() into the appropriate log.isLevelEnabled guard, depending on the underlying framework

Those transformations support two parameters:

value (default log ) corresponds to the name of the logger field

category (defaults to the class name) is the name of the logger category

It’s worth noting that annotating a class with one of those annotations doesn’t prevent you from using the logging framework using the normal long-hand approach.

The first logging AST transformation available is the @Log annotation which relies on the JDK logging framework. Writing:

is equivalent to writing:

Groovy supports the Apache Commons Logging framework using the @Commons annotation. Writing:

You still need to add the appropriate commons-logging jar to your classpath.

Groovy supports the Apache Log4j 1.x framework using the @Log4j annotation. Writing:

You still need to add the appropriate log4j jar to your classpath. This annotation can also be used with the compatible reload4j log4j drop-in replacement, just use the jar from that project instead of a log4j jar.

Groovy supports the Apache Log4j 2.x framework using the @Log4j2 annotation. Writing:

You still need to add the appropriate log4j2 jar to your classpath.

Groovy supports the Simple Logging Facade for Java (SLF4J) framework using the @Slf4j annotation. Writing:

You still need to add the appropriate slf4j jar(s) to your classpath.

Groovy supports the Java Platform Logging API and Service framework using the @PlatformLog annotation. Writing:

You need to be using JDK 9+ to use this capability.

Declarative concurrency

The Groovy language provides a set of annotations aimed at simplifying common concurrency patterns in a declarative approach.

The @Synchronized AST transformations works in a similar way to the synchronized keyword but locks on different objects for safer concurrency. It can be applied on any method or static method:

Writing this is equivalent to creating a lock object and wrapping the whole method into a synchronized block:

By default, @Synchronized creates a field named $lock (or $LOCK for a static method) but you can make it use any field you want by specifying the value attribute, like in the following example:

The @WithReadLock AST transformation works in conjunction with the @WithWriteLock transformation to provide read/write synchronization using the ReentrantReadWriteLock facility that the JDK provides. The annotation can be added to a method or a static method. It will transparently create a $reentrantLock final field (or $REENTRANTLOCK for a static method) and proper synchronization code will be added. For example, the following code:

is equivalent to this:

Both @WithReadLock and @WithWriteLock support specifying an alternative lock object. In that case, the referenced field must be declared by the user, like in the following alternative:

For details

See Javadoc for groovy.transform.WithReadLock

See Javadoc for groovy.transform.WithWriteLock

Easier cloning and externalizing

Groovy provides two annotations aimed at facilitating the implementation of Cloneable and Externalizable interfaces, respectively named @AutoClone and @AutoExternalize .

The @AutoClone annotation is aimed at implementing the @java.lang.Cloneable interface using various strategies, thanks to the style parameter:

the default AutoCloneStyle.CLONE strategy calls super.clone() first then clone() on each cloneable property

the AutoCloneStyle.SIMPLE strategy uses a regular constructor call and copies properties from the source to the clone

the AutoCloneStyle.COPY_CONSTRUCTOR strategy creates and uses a copy constructor

the AutoCloneStyle.SERIALIZATION strategy uses serialization (or externalization) to clone the object

Each of those strategies have pros and cons which are discussed in the Javadoc for groovy.transform.AutoClone and groovy.transform.AutoCloneStyle .

For example, the following example:

Note that the String properties aren’t explicitly handled because Strings are immutable and the clone() method from Object will copy the String references. The same would apply to primitive fields and most of the concrete subclasses of java.lang.Number .

In addition to cloning styles, @AutoClone supports multiple options:

Attribute Default value Description Example

excludes

Empty list

A list of property or field names that need to be excluded from cloning. A string consisting of a comma-separated field/property names is also allowed. See for details

includeFields

false

By default, only properties are cloned. Setting this flag to true will also clone fields.

The @AutoExternalize AST transformation will assist in the creation of java.io.Externalizable classes. It will automatically add the interface to the class and generate the writeExternal and readExternal methods. For example, this code:

will be converted into:

The @AutoExternalize annotation supports two parameters which will let you slightly customize its behavior:

Attribute Default value Description Example

excludes

Empty list

A list of property or field names that need to be excluded from externalizing. A string consisting of a comma-separated field/property names is also allowed. See for details

includeFields

false

By default, only properties are externalized. Setting this flag to true will also clone fields.

Safer scripting

The Groovy language makes it easy to execute user scripts at runtime (for example using groovy.lang.GroovyShell ), but how do you make sure that a script won’t eat all CPU (infinite loops) or that concurrent scripts won’t slowly consume all available threads of a thread pool? Groovy provides several annotations which are aimed towards safer scripting, generating code which will for example allow you to interrupt execution automatically.

One complicated situation in the JVM world is when a thread can’t be stopped. The Thread#stop method exists but is deprecated (and isn’t reliable) so your only chance lies in Thread#interrupt . Calling the latter will set the interrupt flag on the thread, but it will not stop the execution of the thread. This is problematic because it’s the responsibility of the code executing in the thread to check the interrupt flag and properly exit. This makes sense when you, as a developer, know that the code you are executing is meant to be run in an independent thread, but in general, you don’t know it. It’s even worse with user scripts, who might not even know what a thread is (think of DSLs).

@ThreadInterrupt simplifies this by adding thread interruption checks at critical places in the code:

loops (for, while)

first instruction of a method

first instruction of a closure body

Let’s imagine the following user script:

This is an obvious infinite loop. If this code executes in its own thread, interrupting wouldn’t help: if you join on the thread, then the calling code would be able to continue, but the thread would still be alive, running in background without any ability for you to stop it, slowly causing thread starvation.

One possibility to work around this is to set up your shell this way:

The shell is then configured to automatically apply the @ThreadInterrupt AST transformations on all scripts. This allows you to execute user scripts this way:

The transformation automatically modified user code like this:

The check which is introduced inside the loop guarantees that if the interrupt flag is set on the current thread, an exception will be thrown, interrupting the execution of the thread.

@ThreadInterrupt supports multiple options that will let you further customize the behavior of the transformation:

Attribute Default value Description Example

thrown

Specifies the type of exception which is thrown if the thread is interrupted.

checkOnMethodStart

true

Should an interruption check be inserted at the beginning of each method body. See for details.

applyToAllClasses

true

Should the transformation be applied on all classes of the same source unit (in the same source file). See for details.

applyToAllMembers

true

Should the transformation be applied on all members of class. See for details.

The @TimedInterrupt AST transformation tries to solve a slightly different problem from @groovy.transform.ThreadInterrupt : instead of checking the interrupt flag of the thread, it will automatically throw an exception if the thread has been running for too long.

This annotation does spawn a monitoring thread. Instead, it works in a similar manner as by placing checks at appropriate places in the code. This means that if you have a thread blocked by I/O, it will be interrupted.

Imagine the following user code:

The implementation of the famous Fibonacci number computation here is far from optimized. If it is called with a high n value, it can take minutes to answer. With @TimedInterrupt , you can choose how long a script is allowed to run. The following setup code will allow the user script to run for 1 second at max:

This code is equivalent to annotating a class with @TimedInterrupt like this:

@TimedInterrupt supports multiple options that will let you further customize the behavior of the transformation:

Attribute Default value Description Example

value

Long.MAX_VALUE

Used in combination with to specify after how long execution times out.

unit

TimeUnit.SECONDS

Used in combination with to specify after how long execution times out.

thrown

Specifies the type of exception which is thrown if timeout is reached.

checkOnMethodStart

true

Should an interruption check be inserted at the beginning of each method body. See for details.

applyToAllClasses

true

Should the transformation be applied on all classes of the same source unit (in the same source file). See for details.

applyToAllMembers

true

Should the transformation be applied on all members of class. See for details.

is currently not compatible with static methods!

The last annotation for safer scripting is the base annotation when you want to interrupt a script using a custom strategy. In particular, this is the annotation of choice if you want to use resource management (limit the number of calls to an API, …​). In the following example, user code is using an infinite loop, but @ConditionalInterrupt will allow us to check a quota manager and interrupt automatically the script:

The quota checking is very basic here, but it can be any code:

We can make sure @ConditionalInterrupt works properly using this test code:

Of course, in practice, it is unlikely that @ConditionalInterrupt will be itself added by hand on user code. It can be injected in a similar manner as the example shown in the ThreadInterrupt section, using the org.codehaus.groovy.control.customizers.ASTTransformationCustomizer :

@ConditionalInterrupt supports multiple options that will let you further customize the behavior of the transformation:

Attribute Default value Description Example

value

The closure which will be called to check if execution is allowed. If the closure returns false, execution is allowed. If it returns true, then an exception will be thrown.

thrown

Specifies the type of exception which is thrown if execution should be aborted.

checkOnMethodStart

true

Should an interruption check be inserted at the beginning of each method body. See for details.

applyToAllClasses

true

Should the transformation be applied on all classes of the same source unit (in the same source file). See for details.

applyToAllMembers

true

Should the transformation be applied on all members of class. See for details.

Compiler directives

This category of AST transformations groups annotations which have a direct impact on the semantics of the code, rather than focusing on code generation. With that regards, they can be seen as compiler directives that either change the behavior of a program at compile time or runtime.

The @Field annotation only makes sense in the context of a script and aims at solving a common scoping error with scripts. The following example will for example fail at runtime:

The error that is thrown may be difficult to interpret: groovy.lang.MissingPropertyException: No such property: x. The reason is that scripts are compiled to classes and the script body is itself compiled as a single run() method. Methods which are defined in the scripts are independent, so the code above is equivalent to this:

So def x is effectively interpreted as a local variable, outside of the scope of the line method. The @Field AST transformation aims at fixing this by changing the scope of the variable to a field of the enclosing script:

The resulting, equivalent, code is now:

By default, Groovy visibility rules imply that if you create a field without specifying a modifier, then the field is interpreted as a property:

Should you want to create a package private field instead of a property (private field+getter/setter), then annotate your field with @PackageScope :

The @PackageScope annotation can also be used for classes, methods and constructors. In addition, by specifying a list of PackageScopeTarget values as the annotation attribute at the class level, all members within that class that don’t have an explicit modifier and match the provided PackageScopeTarget will remain package protected. For example to apply to fields within a class use the following annotation:

The @PackageScope annotation is seldom used as part of normal Groovy conventions but is sometimes useful for factory methods that should be visible internally within a package or for methods or constructors provided for testing purposes, or when integrating with third-party libraries which require such visibility conventions.

@Final is essentially an alias for the final modifier. The intention is that you would almost never use the @Final annotation directly (just use final ). However, when creating meta-annotations that should apply the final modifier to the node being annotated, you can mix in @Final , e.g..

The @AutoFinal annotation instructs the compiler to automatically insert the final modifier in numerous places within the annotated node. If applied on a method (or constructor), the parameters for that method (or constructor) will be marked as final. If applied on a class definition, the same treatment will occur for all declared methods and constructors within that class.

It is often considered bad practice to reassign parameters of a method or constructor with its body. By adding the final modifier to all parameter declarations you can avoid this practice entirely. Some programmers feel that adding final everywhere increases the amount of boilerplate code and makes the method signatures somewhat noisy. An alternative might instead be to use a code review process or apply a codenarc rule to give warnings if that practice is observed but these alternatives might lead to delayed feedback during quality checking rather than within the IDE or during compilation. The @AutoFinal annotation aims to maximise compiler/IDE feedback while retaining succinct code with minimum boilerplate noise.

The following example illustrates applying the annotation at the class level:

In this example, the two parameters for the constructor and the single parameter for both the fullname and greeting methods will be final. Attempts to modify those parameters within the constructor or method bodies will be flagged by the compiler.

The following example illustrates applying the annotation at the method level:

Here, the add method will have final parameters but the mult method will remain unchanged.

@AnnotationCollector allows the creation of meta-annotations, which are described in a dedicated section .

@TypeChecked activates compile-time type checking on your Groovy code. See section on type checking for details.

@CompileStatic activates static compilation on your Groovy code. See section on type checking for details.

@CompileDynamic disables static compilation on parts of your Groovy code. See section on type checking for details.

@DelegatesTo is not, technically speaking, an AST transformation. It is aimed at documenting code and helping the compiler in case you are using type checking or static compilation . The annotation is described thoroughly in the DSL section of this guide.

@SelfType is not an AST transformation but rather a marker interface used with traits. See the traits documentation for further details.

Swing patterns

@Bindable is an AST transformation that transforms a regular property into a bound property (according to the JavaBeans specification ). The @Bindable annotation can be placed on a property or a class. To convert all properties of a class into bound properties, on can annotate the class like in this example:

This is equivalent to writing this:

@Bindable therefore removes a lot of boilerplate from your class, dramatically increasing readability. If the annotation is put on a single property, only that property is bound:

The @ListenerList AST transformation generates code for adding, removing and getting the list of listeners to a class, just by annotating a collection property:

The transform will generate the appropriate add/remove methods based on the generic type of the list. In addition, it will also create fireXXX methods based on the public methods declared on the class:

@Bindable supports multiple options that will let you further customize the behavior of the transformation:

Attribute Default value Description Example

name

Generic type name

By default, the suffix which will be appended to add/remove/…​ methods is the simple class name of the generic type of the list.

synchronize

false

If set to true, generated methods will be synchronized

The @Vetoable annotation works in a similar manner to @Bindable but generates constrained property according to the JavaBeans specification, instead of bound properties. The annotation can be placed on a class, meaning that all properties will be converted to constrained properties, or on a single property. For example, annotating this class with @Vetoable :

is equivalent to writing this:

If the annotation is put on a single property, only that property is made vetoable:

Test assistance

@NotYetImplemented is used to invert the result of a JUnit 3/4 test case. It is in particular useful if a feature is not yet implemented but the test is. In that case, it is expected that the test fails. Marking it with @NotYetImplemented will inverse the result of the test, like in this example:

Another advantage of using this technique is that you can write test cases for bugs before knowing how to fix them. If some time in the future, a modification in the code fixes a bug by side effect, you’ll be notified because a test which was expected to fail passed.

@ASTTest is a special AST transformation meant to help debugging other AST transformations or the Groovy compiler itself. It will let the developer "explore" the AST during compilation and perform assertions on the AST rather than on the result of compilation. This means that this AST transformations gives access to the AST before the bytecode is produced. @ASTTest can be placed on any annotable node and requires two parameters:

phase : sets at which phase at which @ASTTest will be triggered. The test code will work on the AST tree at the end of this phase.

value : the code which will be executed once the phase is reached, on the annotated node

Compile phase has to be chosen from one of . However, since it is not possible to annotate a node twice with the same annotation, you will not be able to use on the same node at two distinct compile phases.

value is a closure expression which has access to a special variable node corresponding to the annotated node, and a helper lookup method which will be discussed here . For example, you can annotate a class node like this:

we’re checking the state of the Abstract Syntax Tree after the CONVERSION phase
node refers to the AST node which is annotated by @ASTTest
it can be used to perform assertions at compile time

One interesting feature of @ASTTest is that if an assertion fails, then compilation will fail . Now imagine that we want to check the behavior of an AST transformation at compile time. We will take @PackageScope here, and we will want to verify that a property annotated with @PackageScope becomes a package private field. For this, we have to know at which phase the transform runs, which can be found in org.codehaus.groovy.transform.PackageScopeASTTransformation : semantic analysis. Then a test can be written like this:

The @ASTTest annotation can only be placed wherever the grammar allows it. Sometimes, you would like to test the contents of an AST node which is not annotable. In this case, @ASTTest provides a convenient lookup method which will search the AST for nodes which are labelled with a special token:

returns the list of AST nodes which label is 'anchor'
it is always necessary to choose which element to process since lookup always returns a list

Imagine, for example, that you want to test the declared type of a for loop variable. Then you can do it like this:

@ASTTest also exposes those variables inside the test closure:

node corresponds to the annotated node, as usual

compilationUnit gives access to the current org.codehaus.groovy.control.CompilationUnit

compilePhase returns the current compile phase ( org.codehaus.groovy.control.CompilePhase )

The latter is interesting if you don’t specify the phase attribute. In that case, the closure will be executed after each compile phase after (and including) SEMANTIC_ANALYSIS . The context of the transformation is kept after each phase, giving you a chance to check what changed between two phases.

As an example, here is how you could dump the list of AST transformations registered on a class node:

And here is how you can memorize variables for testing between two phases:

if the current compile phase is instruction selection
then we want to make sure was added at
otherwise, if exists and that the variable from the context, is null
then it means that this compile phase is the one where was added

Grape handling

Grape is a dependency management engine embedded into Groovy, relying on several annotations which are described thoroughly in this section of the guide .

Developing AST transformations

There are two kinds of transformations: global and local transformations.

Global transformations are applied to by the compiler on the code being compiled, wherever the transformation apply. Compiled classes that implement global transformations are in a JAR added to the classpath of the compiler and contain service locator file META-INF/services/org.codehaus.groovy.transform.ASTTransformation with a line with the name of the transformation class. The transformation class must have a no-args constructor and implement the org.codehaus.groovy.transform.ASTTransformation interface. It will be run against every source in the compilation , so be sure to not create transformations which scan all the AST in an expansive and time-consuming manner, to keep the compiler fast.

Local transformations are transformations applied locally by annotating code elements you want to transform. For this, we reuse the annotation notation, and those annotations should implement org.codehaus.groovy.transform.ASTTransformation . The compiler will discover them and apply the transformation on these code elements.

Groovy AST transformations must be performed in one of the nine defined compilation phases ( org.codehaus.groovy.control.CompilePhase ).

Global transformations may be applied in any phase, but local transformations may only be applied in the semantic analysis phase or later. Briefly, the compiler phases are:

Initialization : source files are opened and environment configured

Parsing : the grammar is used to produce tree of tokens representing the source code

Conversion : An abstract syntax tree (AST) is created from token trees.

Semantic Analysis : Performs consistency and validity checks that the grammar can’t check for, and resolves classes.

Canonicalization : Complete building the AST

Instruction Selection : instruction set is chosen, for example Java 6 or Java 7 bytecode level

Class Generation : creates the bytecode of the class in memory

Output : write the binary output to the file system

Finalization : Perform any last cleanup

Generally speaking, there is more type information available later in the phases. If your transformation is concerned with reading the AST, then a later phase where information is more plentiful might be a good choice. If your transformation is concerned with writing AST, then an earlier phase where the tree is more sparse might be more convenient.

Local AST transformations are relative to the context they are applied to. In most cases, the context is defined by an annotation that will define the scope of the transform. For example, annotating a field would mean that the transformation applies to the field, while annotating the class would mean that the transformation applies to the whole class.

As a naive and simple example, consider wanting to write a @WithLogging transformation that would add console messages at the start and end of a method invocation. So the following "Hello World" example would actually print "Hello World" along with a start and stop message:

A local AST transformation is an easy way to do this. It requires two things:

a definition of the @WithLogging annotation

an implementation of org.codehaus.groovy.transform.ASTTransformation that adds the logging expressions to the method

An ASTTransformation is a callback that gives you access to the org.codehaus.groovy.control.SourceUnit , through which you can get a reference to the org.codehaus.groovy.ast.ModuleNode (AST).

The AST (Abstract Syntax Tree) is a tree structure consisting mostly of org.codehaus.groovy.ast.expr.Expression (expressions) or org.codehaus.groovy.ast.expr.Statement (statements). An easy way to learn about the AST is to explore it in a debugger. Once you have the AST, you can analyze it to find out information about the code or rewrite it to add new functionality.

The local transformation annotation is the simple part. Here is the @WithLogging one:

The annotation retention can be SOURCE because you won’t need the annotation past that. The element type here is METHOD , the @WithLogging because the annotation applies to methods.

But the most important part is the @GroovyASTTransformationClass annotation. This links the @WithLogging annotation to the ASTTransformation class you will write. gep.WithLoggingASTTransformation is the fully qualified class name of the ASTTransformation we are going to write. This line wires the annotation to the transformation.

With this in place, the Groovy compiler is going to invoke gep.WithLoggingASTTransformation every time an @WithLogging is found in a source unit. Any breakpoint set within LoggingASTTransformation will now be hit within the IDE when running the sample script.

The ASTTransformation class is a little more complex. Here is the very simple, and very naive, transformation to add a method start and stop message for @WithLogging :

even if not mandatory, if you write an AST transformation in Groovy, it is highly recommended to use because it will improve performance of the compiler.
annotate with to tell at which compilation phase the transform needs to run. Here, it’s at the phase.
implement the interface
which only has a single method
the parameter is a 2 AST node array, for which the first one is the annotation node ( ) and the second one is the annotated node (the method node)
create a statement that will print a message when we enter the method
create a statement that will print a message when we exit the method
get the method body, which in this case is a
add the enter method message before the first statement of existing code
append the exit method message after the last statement of existing code
creates an wrapping a corresponding to

It is important to notice that for the brevity of this example, we didn’t make the necessary checks, such as checking that the annotated node is really a MethodNode , or that the method body is an instance of BlockStatement . This exercise is left to the reader.

Note the creation of the new println statements in the createPrintlnAst(String) method. Creating AST for code is not always simple. In this case we need to construct a new method call, passing in the receiver/variable, the name of the method, and an argument list. When creating AST, it might be helpful to write the code you’re trying to create in a Groovy file and then inspect the AST of that code in the debugger to learn what to create. Then write a function like createPrintlnAst using what you learned through the debugger.

In the end:

It is important to note that an AST transformation participates directly in the compilation process. A common error by beginners is to have the AST transformation code in the same source tree as a class that uses the transformation. Being in the same source tree in general means that they are compiled at the same time. Since the transformation itself is going to be compiled in phases and that each compile phase processes all files of the same source unit before going to the next one, there’s a direct consequence: the transformation will not be compiled before the class that uses it! In conclusion, AST transformations need to be precompiled before you can use them. In general, it is as easy as having them in a separate source tree.

Global AST transformation are similar to local one with a major difference: they do not need an annotation, meaning that they are applied globally , that is to say on each class being compiled. It is therefore very important to limit their use to last resort, because it can have a significant impact on the compiler performance.

Following the example of the local AST transformation , imagine that we would like to trace all methods, and not only those which are annotated with @WithLogging . Basically, we need this code to behave the same as the one annotated with @WithLogging before:

To make this work, there are two steps:

create the org.codehaus.groovy.transform.ASTTransformation descriptor inside the META-INF/services directory

create the ASTTransformation implementation

The descriptor file is required and must be found on classpath. It will contain a single line:

The code for the transformation looks similar to the local case, but instead of using the ASTNode[] parameter, we need to use the SourceUnit instead:

even if not mandatory, if you write an AST transformation in Groovy, it is highly recommended to use because it will improve performance of the compiler.
annotate with to tell at which compilation phase the transform needs to run. Here, it’s at the phase.
implement the interface
which only has a single method
the parameter gives access to the source being compiled, so we get the AST of the current source and retrieve the list of methods from this file
we iterate on each method from the source file
create a statement that will print a message when we enter the method
create a statement that will print a message when we exit the method
get the method body, which in this case is a
add the enter method message before the first statement of existing code
append the exit method message after the last statement of existing code
creates an wrapping a corresponding to

AST API guide

While you have seen that you can directly implement the ASTTransformation interface, in almost all cases you will not do this but extend the org.codehaus.groovy.transform.AbstractASTTransformation class. This class provides several utility methods that make AST transformations easier to write. Almost all AST transformations included in Groovy extend this class.

It is a common use case to be able to transform an expression into another. Groovy provides a class which makes it very easy to do this: org.codehaus.groovy.ast.ClassCodeExpressionTransformer

To illustrate this, let’s create a @Shout transformation that will transform all String constants in method call arguments into their uppercase version. For example:

should print:

Then the code for the transformation can use the ClassCodeExpressionTransformer to make this easier:

Internally the transformation creates a
The transformer needs to return the source unit
if a constant expression of type string is detected inside an argument list, transform it into its upper case version
call the transformer on the method being annotated
Writing an AST transformation requires a deep knowledge of the internal Groovy API. In particular it requires knowledge about the AST classes. Since those classes are internal, there are chances that the API will change in the future, meaning that your transformations break. Despite that warning, the AST has been very stable over time and such a thing rarely happens.

Classes of the Abstract Syntax Tree belong to the org.codehaus.groovy.ast package. It is recommended to the reader to use the Groovy Console, in particular the AST browser tool, to gain knowledge about those classes. Another resource for learning is the AST Builder test suite.

Until version 2.5.0, when developing AST transformations, developers should have a deep knowledge about how the AST (Abstract Syntax Tree) was built by the compiler in order to know how to add new expressions or statements during compile time.

Although the use of org.codehaus.groovy.ast.tool.GeneralUtils static methods could mitigate the burden of creating expressions and statements, it’s still a low-level way of writing those AST nodes directly. We needed something to abstract us from writing the AST directly and that’s exactly what Groovy macros were made for. They allow you to directly add code during compilation, without having to translate the code you had in mind to the org.codehaus.groovy.ast.* node related classes.

Let’s see an example, lets create a local AST transformation: @AddMessageMethod . When applied to a given class it will add a new method called getMessage to that class. The method will return "42". The annotation is pretty straight forward:

What would the AST transformation look like without the use of a macro ? Something like this:

Create a return statement
Create a constant expression "42"
Adding the code to the new method
Adding the new method to the annotated class

If you’re not used to the AST API, that definitely doesn’t look like the code you had in mind. Now look how the previous code simplifies with the use of macros.

Much simpler. You wanted to add a return statement that returned "42" and that’s exactly what you can read inside the utility method. Your plain code will be translated for you to a
Adding the return statement to the new method
Adding the new code to the annotated class

Although the macro method is used in this example to create a statement the macro method could also be used to create expressions as well, it depends on which macro signature you use:

macro(Closure) : Create a given statement with the code inside the closure.

macro(Boolean,Closure) : if true wrap expressions inside the closure inside a statement, if false then return an expression

macro(CompilePhase, Closure) : Create a given statement with the code inside the closure in a specific compile phase

macro(CompilePhase, Boolean, Closure) : Create a statement or an expression (true == statement, false == expression) in a specific compilation phase.

All these signatures can be found at

Sometimes we could be only interested in creating a given expression, not the whole statement, in order to do that we should use any of the macro invocations with a boolean parameter:

We’re telling macro not to wrap the expression in a statement, we’re only interested in the expression
Assigning the expression
Creating a using a method from and returning the expression
Adding the code to the new method
Adding the method to the class

Macros are great but we can’t create anything useful or reusable if our macros couldn’t receive parameters or resolve surrounding variables.

In the following example we’re creating an AST transformation @MD5 that when applied to a given String field will add a method returning the MD5 value of that field.

And the transformation:

We need a reference to a variable expression
If using a class outside the standard packages we should add any needed imports or use the qualified name. When using the qualified name of a given static method you need to make sure it’s resolved in the proper compile phase. In this particular case we’re instructing the macro to resolve it at the SEMANTIC_ANALYSIS phase, which is the first compile phase with type information.
In order to substitute any inside the macro we need to use the method. receives a closure as an argument, and the closure is only allowed to substitute expressions, meaning classes inheriting .

As we mentioned earlier, the macro method is only capable of producing statements and expressions . But what if we want to produce other types of nodes, such as a method, a field and so on?

org.codehaus.groovy.macro.transform.MacroClass can be used to create classes (ClassNode instances) in our transformations the same way we created statements and expressions with the macro method before.

The next example is a local transformation @Statistics . When applied to a given class, it will add two methods getMethodCount() and getFieldCount() which return how many methods and fields within the class respectively. Here is the marker annotation.

And the AST transformation:

Creating a template class
Adding template class methods to the annotated class
Passing the reference class
Extracting reference class method count value expression
Extracting reference class field count value expression
Building the method using reference’s method count value expression
Building the method using reference’s field count value expression

Basically we’ve created the Statistics class as a template to avoid writing low level AST API, then we copied methods created in the template class to their final destination.

Types inside the implementation should be resolved inside, that’s why we had to write instead of simply writing .
Notice that we’re using . That’s because the way we use is like we were actually implementing it. So if you were using it will complain because an implementation of an abstract class can’t be another different class.

You have seen that by using macro you can save yourself a lot of work but you might wonder where that method came from. You didn’t declare it or static import it. You can think of it as a special global method (or if you prefer, a method on every Object ). This is much like how the println extension method is defined. But unlike println which becomes a method selected for execution later in the compilation process, macro expansion is done early in the compilation process. The declaration of macro as one of the available methods for this early expansion is done by annotating a macro method definition with the @Macro annotation and making that method available using a similar mechanism for extension modules. Such methods are known as macro methods and the good news is you can define your own.

To define your own macro method, create a class in a similar way to an extension module and add a method such as:

Now you would register this as an extension module using a org.codehaus.groovy.runtime.ExtensionModule file within the META-INF/groovy directory.

Now, assuming that the class and meta info file are on your classpath, you can use the macro method in the following way:

Testing AST transformations

This section is about good practices in regard to testing AST transformations. Previous sections highlighted the fact that to be able to execute an AST transformation, it has to be precompiled. It might sound obvious but a lot of people get caught on this, trying to use an AST transformation in the same source tree as where it is defined.

The first tip for testing AST transformation is therefore to separate test sources from the sources of the transform. Again, this is nothing but best practices, but you must make sure that your build too does actually compile them separately. This is the case by default with both Apache Maven and Gradle .

It is very handy to be able to put a breakpoint in an AST transformation, so that you can debug your code in the IDE. However, you might be surprised to see that your IDE doesn’t stop on the breakpoint. The reason is actually simple: if your IDE uses the Groovy compiler to compile the unit tests for your AST transformation, then the compilation is triggered from the IDE, but the process which will compile the files doesn’t have debugging options. It’s only when the test case is executed that the debugging options are set on the virtual machine. In short: it is too late, the class has been compiled already, and your transformation is already applied.

A very easy workaround is to use the GroovyTestCase class which provides an assertScript method. This means that instead of writing this in a test case:

You should write:

The difference is that when you use assertScript , the code in the assertScript block is compiled when the unit test is executed . That is to say that this time, the Subject class will be compiled with debugging active, and the breakpoint is going to be hit.

Sometimes you may want to make assertions over AST nodes; perhaps to filter the nodes, or to make sure a given transformation has built the expected AST node.

Filtering nodes

For instance if you would like to apply a given transformation only to a specific set of AST nodes, you could use ASTMatcher to filter these nodes. The following example shows how to transform a given expression to another. Using ASTMatcher it looks for a specific expression 1 + 1 and it transforms it to 3 . That’s why we called it the @Joking example.

First we create the @Joking annotation that only can be applied to methods:

Then the transformation, that only applies an instance of org.codehaus.groovy.ast.ClassCodeExpressionTransformer to all the expressions within the method code block.

Get the method’s code statement and apply the expression transformer

And this is when the ASTMatcher is used to apply the transformation only to those expressions matching the expression 1 + 1 .

Builds the expression used as reference pattern
Checks the current expression evaluated matches the reference expression
If it matches then replaces the current expression with the expression built with

Then you could test the implementation as follows:

Unit testing AST transforms

Normally we test AST transformations just checking that the final use of the transformation does what we expect. But it would be great if we could have an easy way to check, for example, that the nodes the transformation adds are what we expected from the beginning.

The following transformation adds a new method giveMeTwo to an annotated class.

Adding the method to the annotated class
Building a binary expression. The binary expression uses the same variable expression in both sides of the token (check method at ).
Builds a new with a method called which returns the result of an expression passed as parameter.

Now instead of creating a test executing the transformation over a given sample code. I would like to check that the construction of the binary expression is done properly:

Using ASTMatcher as a category
Build a template node
Apply some constraints to that template node
Tells compiler that is a placeholder.
Asserts reference node and current node are equal

Of course you can/should always check the actual execution:

Last but not least, testing an AST transformation is also about testing the state of the AST during compilation . Groovy provides a tool named @ASTTest for this: it is an annotation that will let you add assertions on an abstract syntax tree. Please check the documentation for ASTTest for more details.

If you are interested in a step-by-step tutorial about writing AST transformations, you can follow this workshop .

3.5. Dependency management with Grape

3.5.1. quick start.

Grape is a JAR dependency manager embedded into Groovy. Grape lets you quickly add maven repository dependencies to your classpath, making scripting even easier. The simplest use is as simple as adding an annotation to your script:

@Grab also supports a shorthand notation:

Note that we are using an annotated import here, which is the recommended way. You can also search for dependencies on mvnrepository.com and it will provide you the @Grab annotation form of the pom.xml entry.

Not all dependencies are in maven central. You can add new ones like this:

Some maven dependencies need classifiers in order to be able to resolve. You can fix that like this:

Sometimes you will want to exclude transitive dependencies as you might be already using a slightly different but compatible version of some artifact. You can do this as follows:

Because of the way JDBC drivers are loaded, you’ll need to configure Grape to attach JDBC driver dependencies to the system class loader. I.e:

From groovysh use the method call variant:

If you are behind a firewall and/or need to use Groovy/Grape through a proxy server, you can specify those settings on the command like via the http.proxyHost and http.proxyPort system properties:

Or you can make this system-wide by adding these properties to your JAVA_OPTS environment variable:

If you want to see what Grape is doing set the system property groovy.grape.report.downloads to true (e.g. add -Dgroovy.grape.report.downloads=true to invocation or JAVA_OPTS) and Grape will print the following infos to System.error:

Starting resolve of a dependency

Starting download of an artifact

Retrying download of an artifact

Download size and time for downloaded artifacts

To log with even more verbosity, increase the Ivy log level (defaults to -1 ). For example -Divy.message.logger.level=4 .

Grape (The Groovy Adaptable Packaging Engine or Groovy Advanced Packaging Engine ) is the infrastructure enabling the grab() calls in Groovy, a set of classes leveraging Ivy to allow for a repository driven module system for Groovy. This allows a developer to write a script with an essentially arbitrary library requirement, and ship just the script. Grape will, at runtime, download as needed and link the named libraries and all dependencies forming a transitive closure when the script is run from existing repositories such as Maven Central.

Grape follows the Ivy conventions for module version identification, with naming change.

group - Which module group the module comes from. Translates directly to a Maven groupId or an Ivy Organization. Any group matching /groovy[x][\..*]^/ is reserved and may have special meaning to the groovy endorsed modules.

module - The name of the module to load. Translated directly to a Maven artifactId or an Ivy artifact.

version - The version of the module to use. Either a literal version `1.1-RC3' or an Ivy Range `[2.2.1,)' meaning 2.2.1 or any greater version).

classifier - The optional classifier to use (for example, jdk15 )

The downloaded modules will be stored according to Ivy’s standard mechanism with a cache root of ~/.groovy/grapes

3.5.3. Usage

One or more groovy.lang.Grab annotations can be added at any place that annotations are accepted to tell the compiler that this code relies on the specific library. This will have the effect of adding the library to the classloader of the groovy compiler. This annotation is detected and evaluated before any other resolution of classes in the script, so imported classes can be properly resolved by a @Grab annotation.

An appropriate grab(…​) call will be added to the static initializer of the class of the containing class (or script class in the case of an annotated script element).

In early versions of Groovy, if you wanted to use a Grab annotation multiple times on the same node you had to use the @Grapes annotation, e.g.:

Otherwise you’d encounter the following error:

But in recent versions, @Grapes is purely optional.

Technical notes:

Originally, Groovy stored the Grab annotations for access at runtime and duplicates aren’t allowed in the bytecode. In current versions, @Grab has only SOURCE retention, so the multiple occurrences aren’t an issue.

Future versions of Grape may support using the Grapes annotation to provide a level of structuring, e.g. allowing a GrabExclude or GrabResolver annotation to apply to only a subset of the Grab annotations.

Method call

Typically a call to grab will occur early in the script or in class initialization. This is to ensure that the libraries are made available to the ClassLoader before the groovy code relies on the code. A couple of typical calls may appear as follows:

Multiple calls to grab in the same context with the same parameters should be idempotent. However, if the same code is called with a different ClassLoader context then resolution may be re-run.

If the args map passed into the grab call has an attribute noExceptions that evaluates true no exceptions will be thrown.

grab requires that a RootLoader or GroovyClassLoader be specified or be in the ClassLoader chain of the calling class. By default failure to have such a ClassLoader available will result in module resolution and an exception being thrown

The ClassLoader passed in via the classLoader: argument and its parent classloaders.

The ClassLoader of the object passed in as the referenceObject: argument, and its parent classloaders.

The ClassLoader of the class issuing the call to grab

group: - <String> - Which module group the module comes from. Translates directly to a Maven groupId. Any group matching /groovy(|\..|x|x\..)/ is reserved and may have special meaning to the groovy endorsed modules.

module: - <String> - The name of the module to load. Translated directly to a Maven artifactId.

version: - <String> and possibly <Range> - The version of the module to use. Either a literal version `1.1-RC3' or an Ivy Range `[2.2.1,)' meaning 2.2.1 or any greater version).

classifier: - <String> - The Maven classifier to resolve by.

conf: - <String>, default default' - The configuration or scope of the module to download. The default conf is `default: which maps to the maven runtime and master scopes.

force: - <boolean>, defaults true - Used to indicate that this revision must be used in case of conflicts, independently of

conflicts manager

changing: - <boolean>, default false - Whether the artifact can change without its version designation changing.

transitive: - <boolean>, default true - Whether to resolve other dependencies this module has or not.

There are two principal variants of grab , one with a single Map and one with an arguments Map and multiple dependencies map. A call to the single map grab is the same as calling grab with the same map passed in twice, so grab arguments and dependencies can be mixed in the same map, and grab can be called as a single method with named parameters.

There are synonyms for these parameters. Submitting more than one is a runtime exception.

group: , groupId: , organisation: , organization: , org:

module: , artifactId: , artifact:

version: , revision: , rev:

conf: , scope: , configuration:

classLoader: - <GroovyClassLoader> or <RootClassLoader> - The ClassLoader to add resolved Jars to

refObject: - <Object> - The closest parent ClassLoader for the object’s class will be treated as though it were passed in as classLoader:

validate: - <boolean>, default false - Should poms or ivy files be validated (true), or should we trust the cache (false).

noExceptions: - <boolean>, default false - If ClassLoader resolution or repository querying fails, should we throw an exception (false) or fail silently (true).

Grape added a command line executable `grape' that allows for the inspection and management of the local grape cache.

This installs the specified groovy module or maven artifact. If a version is specified that specific version will be installed, otherwise the most recent version will be used (as if `*' we passed in).

Lists locally installed modules (with their full maven name in the case of groovy modules) and versions.

This returns the file locations of the jars representing the artifacts for the specified module(s) and the respective transitive dependencies. You may optionally pass in -ant, -dos, or -shell to get the dependencies expressed in a format applicable for an ant script, windows batch file, or unix shell script respectively. -ivy may be passed to see the dependencies expressed in an ivy like format.

This uninstalls a particular grape: it non-transitively removes the respective jar file from the grape cache.

Advanced configuration

If you need to change the directory grape uses for downloading libraries you can specify the grape.root system property to change the default (which is ~/.groovy/grapes)

You can customize the ivy settings that Grape uses by creating a ~/.groovy/grapeConfig.xml file. If no such file exists, here are the default settings used by Grape.

For more information on how to customize these settings, please refer to the Ivy documentation .

Using Apache Commons Collections:

Using TagSoup:

Using Google Collections:

Launching a Jetty server to serve Groovy templates:

Grape will download Jetty and its dependencies on first launch of this script, and cache them. We create a new Jetty Server on port 8080, then expose Groovy’s TemplateServlet at the root of the context — Groovy comes with its own powerful template engine mechanism. We start the server and let it run for a certain duration. Each time someone will hit http://localhost:8080/somepage.gsp, it will display the somepage.gsp template to the user — those template pages should be situated in the same directory as this server script.

3.6. Testing Guide

The Groovy programming language comes with great support for writing tests. In addition to the language features and test integration with state-of-the-art testing libraries and frameworks, the Groovy ecosystem has born a rich set of testing libraries and frameworks.

This chapter will start with language specific testing features and continue with a closer look at JUnit integration, Spock for specifications, and Geb for functional tests. Finally, we’ll do an overview of other testing libraries known to be working with Groovy.

3.6.2. Language Features

Besides integrated support for JUnit, the Groovy programming language comes with features that have proven to be very valuable for test-driven development. This section gives insight on them.

Writing tests means formulating assumptions by using assertions. In Java this can be done by using the assert keyword that has been added in J2SE 1.4. In Java, assert statements can be enabled via the JVM parameters -ea (or -enableassertions ) and -da (or -disableassertions ). Assertion statements in Java are disabled by default.

Groovy comes with a rather powerful variant of assert also known as power assertion statement . Groovy’s power assert differs from the Java version in its output given the boolean expression validates to false :

This section shows the std-err output

The java.lang.AssertionError that is thrown whenever the assertion can not be validated successfully, contains an extended version of the original exception message. The power assertion output shows evaluation results from the outer to the inner expression.

The power assertion statements true power unleashes in complex Boolean statements, or statements with collections or other toString -enabled classes:

Another important difference from Java is that in Groovy assertions are enabled by default . It has been a language design decision to remove the possibility to deactivate assertions. Or, as Bertrand Meyer stated, it makes no sense to take off your swim ring if you put your feet into real water .

One thing to be aware of are methods with side effects inside Boolean expressions in power assertion statements. As the internal error message construction mechanism does only store references to instances under target, it happens that the error message text is invalid at rendering time in case of side-effecting methods involved:

The error message shows the actual state of the collection, not the state before the method was applied
If you choose to provide a custom assertion error message this can be done by using the Java syntax where is the Boolean expression and is the custom error message. Be aware though that this will disable the power assert and will fully fall back to custom error messages on assertion errors.

Mocking and Stubbing

Groovy has excellent built-in support for a range of mocking and stubbing alternatives. When using Java, dynamic mocking frameworks are very popular. A key reason for this is that it is hard work creating custom hand-crafted mocks using Java. Such frameworks can be used easily with Groovy if you choose but creating custom mocks is much easier in Groovy. You can often get away with simple maps or closures to build your custom mocks.

The following sections show ways to create mocks and stubs with Groovy language features only.

By using maps or expandos, we can incorporate desired behaviour of a collaborator very easily as shown here:

The as operator can be used to coerce a map to a particular class. The given map keys are interpreted as method names and the values, being groovy.lang.Closure blocks, are interpreted as method code blocks.

Be aware that map coercion can get into the way if you deal with custom descendant classes in combination with the operator. The map coercion mechanism is targeted directly at certain collection classes, it doesn’t take custom classes into account.

The 'as' operator can be used with closures in a neat way which is great for developer testing in simple scenarios. We haven’t found this technique to be so powerful that we want to do away with dynamic mocking, but it can be very useful in simple cases none-the-less.

Classes or interfaces holding a single method, including SAM (single abstract method) classes, can be used to coerce a closure block to be an object of the given type. Be aware that for doing this, Groovy internally create a proxy object descending for the given class. So the object will not be a direct instance of the given class. This important if, for example, the generated proxy object’s metaclass is altered afterwards.

Let’s have an example on coercing a closure to be of a specific type:

Groovy supports a feature called implicit SAM coercion. This means that the as operator is not necessary in situations where the runtime can infer the target SAM type. This type of coercion might be useful in tests to mock entire SAM classes:

The Groovy mocking and stubbing classes can be found in the groovy.mock.interceptor package.

The MockFor class supports (typically unit) testing of classes in isolation by allowing a strictly ordered expectation of the behavior of collaborators to be defined. A typical test scenario involves a class under test and one or more collaborators. In such a scenario it is often desirable to just test the business logic of the class under test. One strategy for doing that is to replace the collaborator instances with simplified mock objects to help isolate out the logic in the test target. MockFor allows such mocks to be created using meta-programming. The desired behavior of collaborators is defined as a behavior specification. The behavior is enforced and checked automatically.

Let’s assume our target classes looked like this:

With MockFor , a mock expectation is always sequence dependent and its use automatically ends with a call to verify :

a new mock is created by a new instance of
a is passed to which enables the mocking functionality
a call to checks whether the sequence and number of method calls is as expected

The StubFor class supports (typically unit) testing of classes in isolation by allowing a loosely-ordered expectation of the behavior of collaborators to be defined. A typical test scenario involves a class under test and one or more collaborators. In such a scenario it is often desirable to just test the business logic of the CUT. One strategy for doing that is to replace the collaborator instances with simplified stub objects to help isolate out the logic in the target class. StubFor allows such stubs to be created using meta-programming. The desired behavior of collaborators is defined as a behavior specification.

In contrast to MockFor the stub expectation checked with verify is sequence independent and its use is optional:

a new stub is created by a new instance of
the method is used for delegating all calls inside the closure to the instance
a is passed to which enables the stubbing functionality
a call to (optional) checks whether the number of method calls is as expected

MockFor and StubFor can not be used to test statically compiled classes e.g. for Java classes or Groovy classes that make use of @CompileStatic . To stub and/or mock these classes you can use Spock or one of the Java mocking libraries.

Groovy includes a special MetaClass the so-called ExpandoMetaClass (EMC). It allows to dynamically add methods, constructors, properties and static methods using a neat closure syntax.

Every java.lang.Class is supplied with a special metaClass property that will give a reference to an ExpandoMetaClass instance. The expando metaclass is not restricted to custom classes, it can be used for JDK classes like for example java.lang.String as well:

The ExpandoMetaClass is a rather good candidate for mocking functionality as it allows for more advanced stuff like mocking static methods

or even constructors

Mocking constructors might seem like a hack that’s better not even to be considered but even there might be valid use cases. An example can be found in Grails where domain class constructors are added at run-time with the help of . This lets the domain object register itself in the Spring application context and allows for injection of services or other beans controlled by the dependency-injection container.

If you want to change the metaClass property on a per test method level you need to remove the changes that were done to the metaclass, otherwise those changes would be persistent across test method calls. Changes are removed by replacing the metaclass in the GroovyMetaClassRegistry :

Another alternative is to register a MetaClassRegistryChangeEventListener , track the changed classes and remove the changes in the cleanup method of your chosen testing runtime. A good example can be found in the Grails web development framework .

Besides using the ExpandoMetaClass on a class-level, there is also support for using the metaclass on a per-object level:

In this case the metaclass change is related to the instance only. Depending on the test scenario this might be a better fit than the global metaclass change.

GDK Methods

The following section gives a brief overview on GDK methods that can be leveraged in test case scenarios, for example for test data generation.

The combinations method that is added on java.lang.Iterable compliant classes can be used to get a list of combinations from a list containing two or more sub-lists:

The method could be used in test case scenarios to generate all possible argument combinations for a specific method call.

The eachCombination method that is added on java.lang.Iterable can be used to apply a function (or in this case a groovy.lang.Closure ) to each if the combinations that has been built by the combinations method:

eachCombination is a GDK method that is added to all classes conforming to the java.lang.Iterable interface. It applies a function on each combination of the input lists:

The method could be used in the testing context to call methods with each of the generated combinations.

Tool Support

Code coverage is a useful measure of the effectiveness of (unit) tests. A program with high code coverage has a lower chance to hold critical bugs than a program with no or low coverage. To get code coverage metrics, the generated byte-code usually needs to be instrumented before the tests are executed. One tool with Groovy support for this task is Cobertura .

The following code listing shows an example on how to enable Cobertura test coverage reports in a Gradle build script from a Groovy project:

Several output formats can be chosen for Cobertura coverage reports and test code coverage reports can be added to continuous integration build tasks.

3.6.3. Testing with JUnit

Groovy simplifies JUnit testing in the following ways:

You use the same overall practices as you would when testing with Java but you can adopt much of Groovy’s concise syntax in your tests making them succinct. You can even use the capabilities for writing testing domain specific languages (DSLs) if you feel so inclined.

There are numerous helper classes that simplify many testing activities. The details differ in some cases depending on the version of JUnit you are using. We’ll cover those details shortly.

Groovy’s PowerAssert mechanism is wonderful to use in your tests

Groovy deems that tests are so important you should be able to run them as easily as scripts or classes. This is why Groovy includes an automatic test runner when using the groovy command or the GroovyConsole. This gives you some additional options over and above running your tests

In the following sections we will have a closer look at JUnit 3, 4 and 5 Groovy integration.

Maybe one of the most prominent Groovy classes supporting JUnit 3 tests is the GroovyTestCase class. Being derived from junit.framework.TestCase it offers a bunch of additional methods that make testing in Groovy a breeze.

Although inherits from doesn’t mean you can’t use JUnit 4 features in your project. In fact, the most recent Groovy versions come with a bundled JUnit 4 and that comes with a backwards compatible implementation. There have been some discussion on the Groovy mailing-list on whether to use or JUnit 4 with the result that it is mostly a matter of taste, but with you get a bunch of methods for free that make certain types of tests easier to write.

In this section, we will have a look at some of the methods provided by GroovyTestCase . A full list of these can be found in the JavaDoc documentation for groovy.test.GroovyTestCase , don’t forget it is inherited from junit.framework.TestCase which inherits all the assert* methods.

GroovyTestCase is inherited from junit.framework.TestCase therefore it inherits a large number of assertion methods being available to be called in every test method:

As can be seen above, in contrast to Java it is possible to leave out the parenthesis in most situations which leads to even more readability of JUnit assertion method call expressions.

An interesting assertion method that is added by GroovyTestCase is assertScript . It ensures that the given Groovy code string succeeds without any exception:

shouldFail can be used to check whether the given code block fails or not. In case it fails, the assertion does hold, otherwise the assertion fails:

The example above uses the basic shouldFail method interface that takes a groovy.lang.Closure as a single argument. The Closure instance holds the code that is supposed to be breaking during run-time.

If we wanted to assert shouldFail on a specific java.lang.Exception type we could have done so by using the shouldFail implementation that takes the Exception class as first argument and the Closure as second argument:

If anything other than IndexOutOfBoundsException (or a descendant class of it) is thrown, the test case will fail.

A pretty nice feature of shouldFail hasn’t been visible so far: it returns the exception message. This is really useful if you want to assert on the exception error message:

The notYetImplemented method has been greatly influenced by HtmlUnit. It allows to write a test method but mark it as not yet implemented. As long as the test method fails and is marked with notYetImplemented the test goes green:

a call to is necessary for to get the current method stack.
as long as the test evaluates to the test execution will be successful.

An alternative to the notYetImplemented method is the @NotYetImplemented annotation. It allows for annotating a method as not yet implemented, with the exact same behavior as GroovyTestCase#notYetImplemented but without the need for the notYetImplemented method call:

Groovy can be used to write JUnit 4 test cases without any restrictions. The groovy.test.GroovyAssert holds various static methods that can be used as replacement for the GroovyTestCase methods in JUnit 4 tests:

As can be seen in the example above, the static methods found in GroovyAssert are imported at the beginning of the class definition thus shouldFail can be used the same way it can be used in a GroovyTestCase .

descends from that means it inherits all JUnit assertion methods. However, with the introduction of the power assertion statement, it turned out to be instead of using the JUnit assertion methods with the improved message being the main reason.

It is worth mentioning that GroovyAssert.shouldFail is not absolutely identical to GroovyTestCase.shouldFail . While GroovyTestCase.shouldFail returns the exception message, GroovyAssert.shouldFail returns the exception itself. It takes a few more keystrokes to get the message, but in return you can access other properties and methods of the exception:

Much of the approach and helper classes described under JUnit4 apply when using JUnit5 however JUnit5 uses some slightly different class annotations when writing your tests. See the JUnit5 documentation for more details.

Create your test classes as per normal JUnit5 guidelines as shown in this example:

This test requires the additional dependency if not already in your project.

You can run the tests in your IDE or build tool if it supports and is configured for JUnit5. If you run the above test in the GroovyConsole or via the groovy command, you will see a short text summary of the result of running the test:

More detailed information is available at the FINE logging level. You can configure your logging to display such information or do it programmatically as follows:

3.6.4. Testing with Spock

Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the crowd is its beautiful and highly expressive specification DSL. In practice, Spock specifications are written as Groovy classes. Although written in Groovy they can be used to test Java classes. Spock can be used for unit, integration or BDD (behavior-driven-development) testing, it doesn’t put itself into a specific category of testing frameworks or libraries.

Beside these awesome features Spock is a good example on how to leverage advanced Groovy programming language features in third party libraries, for example, by using Groovy AST transformations.
This section should not serve as detailed guide on how to use Spock, it should rather give an impression what Spock is about and how it can be leveraged for unit, integration, functional or any other type of testing.

The next section we will have a first look at the anatomy of a Spock specification. It should give a pretty good feeling on what Spock is up to.

Spock lets you write specifications that describe features (properties, aspects) exhibited by a system of interest. The "system" can be anything between a single class and an entire application, a more advanced term for it is system under specification . The feature description starts from a specific snapshot of the system and its collaborators, this snapshot is called the feature’s fixture .

Spock specification classes are derived from spock.lang.Specification . A concrete specification class might consist of fields, fixture methods, features methods and helper methods.

Let’s have a look at a simple specification with a single feature method for an imaginary Stack class:

Feature method, is by convention named with a String literal.
Setup block, here is where any setup work for this feature needs to be done.
When block describes a stimulus, a certain action under target by this feature specification.
Then block any expressions that can be used to validate the result of the code that was triggered by the when block.

Spock feature specifications are defined as methods inside a spock.lang.Specification class. They describe the feature by using a String literal instead of a method name.

A feature method holds multiple blocks, in our example we used setup , when and then . The setup block is special in that it is optional and allows to configure local variables visible inside the feature method. The when block defines the stimulus and is a companion of the then block which describes the response to the stimulus.

Note that the setup method in the StackSpec above additionally has a description String. Description Strings are optional and can be added after block labels (like setup , when , then ).

Spock provides much more features like data tables or advanced mocking capabilities. Feel free to consult the Spock GitHub page for more documentation and download information.

3.6.5. Functional Tests with Geb

Geb is a functional web testing and scraper library that integrates with JUnit and Spock. It is based upon the Selenium web drivers and, like Spock, provides a Groovy DSL to write functional tests for web applications.

Geb has great features that make it a good fit for a functional testing library:

DOM access via a JQuery-like $ function

implements the page pattern

support for modularization of certain web components (e.g. menu-bars, etc.) with modules

integration with JavaScript via the JS variable

This section should not serve as detailed guide on how to use Geb, it should rather give an impression what Geb is about and how it can be leveraged functional testing.

The next section will give an example on how Geb can be used to write a functional test for a simple web page with a single search field.

Although Geb can be used standalone in a Groovy script, in many scenarios it’s used in combination with other testing frameworks. Geb comes with various base classes that can be used in JUnit 3, 4, TestNG or Spock tests. The base classes are part of additional Geb modules that need to be added as a dependency.

For example, the following @Grab dependencies can be used to run Geb with the Selenium Firefox driver in JUnit4 tests. The module that is needed for JUnit 3/4 support is geb-junit4 :

The central class in Geb is the geb.Browser class. As its name implies it is used to browse pages and access DOM elements:

A new instance is created. In this case it uses the Selenium and sets the .
is used to navigate to a URL or relative URI
together with CSS selectors is used to access the and DOM fields.

The Browser class comes with a drive method that delegates all method/property calls to the current browser instance. The Browser configuration must not be done inline, it can also be externalized in a GebConfig.groovy configuration file for example. In practice, the usage of the Browser class is mostly hidden by Geb test base classes. They delegate all missing properties and method calls to the current browser instance that exists in the background:

takes a relative or absolute link and calls the page.
is used to access DOM content. Any CSS selectors supported by the underlying Selenium drivers are allowed
is used to click a button.
is used to get the first link out of the block

The example above shows a simple Geb web test with the JUnit 4 base class geb.junit4.GebTest . Note that in this case the Browser configuration is externalized. GebTest delegates methods like go and $ to the underlying browser instance.

In the previous section we only scratched the surface of the available Geb features. More information on Geb can be found at the project homepage .

The Parrot parser is based on antlr4 and introduced since Groovy 3.0.0. It provides the following options to tune parsing performance:

Option Description Default Version Example

groovy.parallel.parse

Parsing groovy source files in parallel.

util Groovy 4.0.0

3.0.5+

-Dgroovy.parallel.parse=true

groovy.antlr4.cache.threshold

antlr4 relies on DFA cache heavily for better performance, so antlr4 will not clear DFA cache, thus OutOfMemoryError will probably occur. Groovy trades off parsing performance and memory usage, when the count of Groovy source files parsed hits the cache threshold, the DFA cache will be cleared. means never clearing DFA cache, so requiring bigger JVM heap size. Or set a greater value, e.g. 200 to clear DFA cache if threshold hits. the threshold specified is the count of groovy source files

3.0.5+

-Dgroovy.antlr4.cache.threshold=200

groovy.antlr4.sll.threshold

Parrot parser will try SLL mode and then try LL mode if SLL failed. But the more tokens to parse, the more likely SLL will fail. If SLL threshold hits, SLL will be skipped. Setting the threshold to means never trying SLL mode, which is not recommended at most cases because SLL is the fastest mode though SLL is less powerful than LL. the threshold specified is the token count

(disabled by default)

3.0.9+

-Dgroovy.antlr4.sll.threshold=1000

groovy.antlr4.clear.lexer.dfa.cache

Clear the DFA cache for lexer. The DFA cache for lexer is always small and important for parsing performance, so it’s strongly recommended to leave it as it is until OutOfMemoryError will truly occur

3.0.9+

-Dgroovy.antlr4.clear.lexer.dfa.cache=true

3.8. Processing JSON

Groovy comes with integrated support for converting between Groovy objects and JSON. The classes dedicated to JSON serialisation and parsing are found in the groovy.json package.

3.8.1. JsonSlurper

JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String .

The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others. For the next example we will use the parseText method. It parses a JSON String and recursively converts it to a list or map of objects. The other parse* methods are similar in that they return a JSON String but for different parameter types.

Notice the result is a plain map and can be handled like a normal Groovy object instance. JsonSlurper parses the given JSON as defined by the ECMA-404 JSON Interchange Standard plus support for JavaScript comments and dates.

In addition to maps JsonSlurper supports JSON arrays which are converted to lists.

The JSON standard supports the following primitive data types: string, number, object, true , false and null . JsonSlurper converts these JSON types into corresponding Groovy types.

As JsonSlurper is returning pure Groovy object instances without any special JSON classes in the back, its usage is transparent. In fact, JsonSlurper results conform to GPath expressions. GPath is a powerful expression language that is supported by multiple slurpers for different data formats ( XmlSlurper for XML being one example).

For more details please have a look at the section on .

The following table gives an overview of the JSON types and the corresponding Groovy data types:

JSON Groovy

string

number

or

object

array

true

false

null

date

based on the date format

Whenever a value in JSON is , supplements it with the Groovy value. This is in contrast to other JSON parsers that represent a value with a library-provided singleton object.

JsonSlurper comes with a couple of parser implementations. Each parser fits different requirements, it could well be that for certain scenarios the JsonSlurper default parser is not the best bet for all situations. Here is an overview of the shipped parser implementations:

The JsonParserCharArray parser basically takes a JSON string and operates on the underlying character array. During value conversion it copies character sub-arrays (a mechanism known as "chopping") and operates on them.

The JsonFastParser is a special variant of the JsonParserCharArray and is the fastest parser. However, it is not the default parser for a reason. JsonFastParser is a so-called index-overlay parser. During parsing of the given JSON String it tries as hard as possible to avoid creating new char arrays or String instances. It keeps pointers to the underlying original character array only. In addition, it defers object creation as late as possible. If parsed maps are put into long-term caches care must be taken as the map objects might not be created and still consist of pointer to the original char buffer only. However, JsonFastParser comes with a special chop mode which dices up the char buffer early to keep a small copy of the original buffer. Recommendation is to use the JsonFastParser for JSON buffers under 2MB and keeping the long-term cache restriction in mind.

The JsonParserLax is a special variant of the JsonParserCharArray parser. It has similar performance characteristics as JsonFastParser but differs in that it isn’t exclusively relying on the ECMA-404 JSON grammar. For example it allows for comments, no quote strings etc.

The JsonParserUsingCharacterSource is a special parser for very large files. It uses a technique called "character windowing" to parse large JSON files (large means files over 2MB size in this case) with constant performance characteristics.

The default parser implementation for JsonSlurper is JsonParserCharArray . The JsonParserType enumeration contains constants for the parser implementations described above:

Implementation Constant

Changing the parser implementation is as easy as setting the JsonParserType with a call to JsonSlurper#setType() .

3.8.2. JsonOutput

JsonOutput is responsible for serialising Groovy objects into JSON strings. It can be seen as companion object to JsonSlurper , being a JSON parser.

JsonOutput comes with overloaded, static toJson methods. Each toJson implementation takes a different parameter type. The static methods can either be used directly or by importing the methods with a static import statement.

The result of a toJson call is a String containing the JSON code.

JsonOutput does not only support primitive, maps or list data types to be serialized to JSON, it goes further and even has support for serialising POGOs, that is, plain-old Groovy objects.

Customizing Output

If you need control over the serialized output you can use a JsonGenerator . The JsonGenerator.Options builder can be used to create a customized generator. One or more options can be set on this builder in order to alter the resulting output. When you are done setting the options simply call the build() method in order to get a fully configured instance that will generate output based on the options selected.

A closure can be used to transform a type. These closure converters are registered for a given type and will be called any time that type or a subtype is encountered. The first parameter to the closure is an object matching the type for which the converter is registered and this parameter is required. The closure may take an optional second String parameter and this will be set to the key name if one is available.

As we saw in previous examples, the JSON output is not pretty printed per default. However, the prettyPrint method in JsonOutput comes to rescue for this task.

prettyPrint takes a String as single parameter; therefore, it can be applied on arbitrary JSON String instances, not only the result of JsonOutput.toJson .

Another way to create JSON from Groovy is to use JsonBuilder or StreamingJsonBuilder . Both builders provide a DSL which allows to formulate an object graph which is then converted to JSON.

For more details on builders, have a look at the builders chapter which covers both and .

3.9. Interacting with a SQL database

Groovy’s groovy-sql module provides a higher-level abstraction over Java’s JDBC technology. JDBC itself provides a lower-level but fairly comprehensive API which provides uniform access to a whole variety of supported relational database systems. We’ll use HSQLDB in our examples here but you can alternatively use Oracle, SQL Server, MySQL and a host of others. The most frequently used class within the groovy-sql module is the groovy.sql.Sql class which raises the JDBC abstractions up one level. We’ll cover that first.

3.9.1. Connecting to the database

Connecting to a database with Groovy’s Sql class requires four pieces of information:

The database uniform resource locator (URL)

The driver class name (which can be derived automatically in some situations)

For our HSQLDB database, the values will be something like that shown in the following table:

Property Value

url

user

sa (or your )

password

driver

Consult the documentation for the JDBC driver that you plan to use to determine the correct values for your situation.

The Sql class has a newInstance factory method which takes these parameters. You would typically use it as follows:

If you don’t want to have to handle resource handling yourself (i.e. call close() manually) then you can use the withInstance variation as shown here:

It is often preferred to use a DataSource. You may have one available to you from a connection pool. Here we’ll use the one provided as part of the HSQLDB driver jar as shown here:

If you have your own connection pooling, the details will be different, e.g. for Apache Commons DBCP:

The previous examples assume that the necessary database driver jar is already on your classpath. For a self-contained script you can add @Grab statements to the top of the script to automatically download the necessary jar as shown here:

The @GrabConfig statement is necessary to make sure the system classloader is used. This ensures that the driver classes and system classes like java.sql.DriverManager are in the same classloader.

3.9.2. Executing SQL

You can execute arbitrary SQL commands using the execute() method. Let’s have a look at using it to create a table.

The simplest way to execute SQL is to call the execute() method passing the SQL you wish to execute as a String as shown here:

There is a variant of this method which takes a GString and another with a list of parameters. There are also other variants with similar names: executeInsert and executeUpdate . We’ll see examples of these variants in other examples in this section.

3.9.3. Basic CRUD operations

The basic operations on a database are Create, Read, Update and Delete (the so-called CRUD operations). We’ll examine each of these in turn.

You can use the same execute() statement we saw earlier but to insert a row by using a SQL insert statement as follows:

You can use a special executeInsert method instead of execute . This will return a list of all keys generated. Both the execute and executeInsert methods allow you to place '?' placeholders into your SQL string and supply a list of parameters. In this case a PreparedStatement is used which avoids any risk of SQL injection. The following example illustrates executeInsert using placeholders and parameters:

In addition, both the execute and executeInsert methods allow you to use GStrings. Any '$' placeholders within the SQL are assumed to be placeholders. An escaping mechanism exists if you want to supply part of the GString with a variable in a position which isn’t where normal placeholders go within SQL. See the GroovyDoc for more details. Also, executeInsert allows you to supply a list of key column names, when multiple keys are returned and you are only interested in some of them. Here is a fragment illustrating key name specification and GStrings:

Reading rows of data from the database is accomplished using one of several available methods: query , eachRow , firstRow and rows .

Use the query method if you want to iterate through the ResultSet returned by the underlying JDBC API as shown here:

Use the eachRow method if you want a slightly higher-level abstraction which provides a Groovy friendly map-like abstraction for the ResultSet as shown here:

Note that you can use Groovy list-style and map-style notations when accessing the row of data.

Use the firstRow method if you for similar functionality as eachRow but returning only one row of data as shown here:

Use the rows method if you want to process a list of map-like data structures as shown here:

Note that the map-like abstraction has case-insensitive keys (hence we can use 'FIRSTNAME' or 'firstname' as the key) and also that -ve indices (a standard Groovy feature) works when using an index value (to count column numbers from the right).

You can also use any of the above methods to return scalar values, though typically firstRow is all that is required in such cases. An example returning the count of rows is shown here:

Updating rows can again be done using the execute() method. Just use a SQL update statement as the argument to the method. You can insert an author with just a lastname and then update the row to also have a firstname as follows:

There is also a special executeUpdate variant which returns the number of rows updated as a result of executing the SQL. For example, you can change the lastname of an author as follows:

The execute method is also used for deleting rows as this example shows:

3.9.4. Advanced SQL operations

The easiest way to perform database operations within a transaction is to include the database operation within a withTransaction closure as shown in the following example:

Here the database starts empty and has two rows after successful completion of the operation. Outside the scope of the transaction, the database is never seen as having just one row.

If something goes wrong, any earlier operations within the withTransaction block are rolled back. We can see that in operation in the following example where we use database metadata (more details coming up shortly) to find the maximum allowable size of the firstname column and then attempt to enter a firstname one larger than that maximum value as shown here:

Even though the first sql execute succeeds initially, it will be rolled back and the number of rows will remain the same.

When dealing with large volumes of data, particularly when inserting such data, it can be more efficient to chunk the data into batches. This is done using the withBatch statement as shown in the following example:

After executing these statements, there will be 7 new rows in the database. In fact, they will have been added in batches even though you can’t easily tell that after that fact. If you want to confirm what is going on under the covers, you can add a little bit of extra logging into your program. Add the following lines before the withBatch statement:

With this extra logging turned on, and the changes made as per the above comment for the logging.properties file, you should see output such as:

We should also note, that any combination of SQL statements can be added to the batch. They don’t all have to be inserting a new row to the same table.

We noted earlier that to avoid SQL injection, we encourage you to use prepared statements, this is achieved using the variants of methods which take GStrings or a list of extra parameters. Prepared statements can be used in combination with batches as shown in the following example:

This provides a much safer option if the data could come from a user such as via a script or a web form. Of course, given that a prepared statement is being used, you are limited to a batch of the same SQL operation (insert in our example) to the one table.

When presenting large tables of data to a user, it is often convenient to present information a page at a time. Many of Groovy’s SQL retrieval methods have extra parameters which can be used to select a particular page of interest. The starting position and page size are specified as integers as shown in the following example using rows :

JDBC metadata can be retrieved in numerous ways. Perhaps the most basic approach is to extract the metadata from any row as shown in the following example which examines the tablename, column names and column type names:

And another slight variant to the previous example, this time also looking at the column label:

Accessing metadata is quite common, so Groovy also provides variants to many of its methods that let you supply a closure that will be called once with the row metadata in addition to the normal row closure which is called for each row. The following example illustrates the two closure variant for eachRow :

Note that our SQL query will only return one row, so we could have equally used firstRow for the previous example.

Finally, JDBC also provides metadata per connection (not just for rows). You can also access such metadata from Groovy as shown in this example:

Consult the JavaDoc for your driver to find out what metadata information is available for you to access.

Groovy supports some additional alternative placeholder syntax variants. The GString variants are typically preferred over these alternatives but the alternatives are useful for Java integration purposes and sometimes in templating scenarios where GStrings might already be in heavy use as part of a template. The named parameter variants are much like the String plus list of parameter variants but instead of having a list of ? placeholders followed by a list of parameters, you have one or more placeholders having the form :propName or ?.propName and a single map, named arguments or a domain object as the parameter. The map or domain object should have a property named propName corresponding to each supplied placeholder.

Here is an example using the colon form:

And another example using the question mark form:

If the information you need to supply is spread across multiple maps or domain objects you can use the question mark form with an additional ordinal index as shown here:

The exact syntax for creating a stored procedure or function varies slightly between different databases. For the HSQLDB database we are using, we can create a stored function which returns the initials of all authors in a table as follows:

We can use a SQL CALL statement to invoke the function using Groovy’s normal SQL retrieval methods. Here is an example using eachRow .

Here is the code for creating another stored function, this one taking the lastname as a parameter:

We can use the placeholder syntax to specify where the parameter belongs and note the special placeholder position to indicate the result:

Finally, here is a stored procedure with input and output parameters:

To use the CONCAT_NAME stored procedure parameter, we make use of a special call method. Any input parameters are simply provided as parameters to the method call. For output parameters, the resulting type must be specified as shown here:

Groovy provides a groovy.sql.DataSet class which enhances the groovy.sql.Sql class with what can be thought of as mini ORM functionality. Databases are accessed and queried using POGO fields and operators rather than JDBC-level API calls and RDBMS column names.

So, instead of a query like:

You can write code like this:

Here we have a helper "domain" class:

Database access and manipulation involves creating or working with instances of the domain class.

3.10. Querying collections in SQL-like style

Groovy’s groovy-ginq module provides a higher-level abstraction over collections. It could perform queries against in-memory collections of objects in SQL-like style. Also, querying XML, JSON, YAML, etc. could also be supported because they can be parsed into collections. As GORM and jOOQ are powerful enough to support querying DB, we will cover collections first.

3.10.1. GINQ a.k.a. Groovy-Integrated Query

GINQ is a DSL for querying with SQL-like syntax, which consists of the following structure:

means the related clause is optional, means zero or more times, and means one or more times. Also, the clauses of GINQ are order sensitive, so the order of clauses should be kept as the above structure

As we could see, the simplest GINQ consists of a from clause and a select clause, which looks like:

clause is required in GINQ. Also, GINQ supports multiple data sources through and the related joins.

As a DSL, GINQ should be wrapped with the following block to be executed:

For example,

And it is strongly recommended to use def to define the variable for the result of GINQ execution, which is a Queryable instance that is lazy.

Currently GINQ can not work well when STC is enabled.

Also, GINQ could be written in a method marked with @GQ :

Mark the ginq method as a GINQ method with @GQ annotation:

Specify the result type as List :

GINQ supports many result types, e.g. , , , , , and array types.

Enable parallel querying:

GINQ Syntax

Data source.

The data source for GINQ could be specified by from clause, which is equivalent to SQL’s FROM . Currently GINQ supports Iterable , Stream , array and GINQ result set as its data source:

The column names could be renamed with as clause:

The renamed column could be referenced by its new name, e.g. . Also, it could be referenced by its index, e.g.
is a simplified syntax of when and only when >= 2. Also, instance will be created if clause is used. The values stored in the could be referenced by their names.

Construct new objects as column values:

distinct is equivalent to SQL’s DISTINCT

where is equivalent to SQL’s WHERE

More data sources for GINQ could be specified by join clauses.

is preferred over and as it has better readability, and it is smart enough to choose the correct concrete join(i.e. or ) by its clause.

hash join is especially efficient when data sources contain lots of objects

Only binary expressions( , ) are allowed in the clause of hash join

groupby is equivalent to SQL’s GROUP BY , and having is equivalent to SQL’s HAVING

The group columns could be renamed with as clause:

GINQ provides some built-in aggregate functions:

Function Argument Type(s) Return Type Description

count()

java.lang.Long

number of rows, similar to in SQL

count( )

any

java.lang.Long

number of rows for which the value of is not

min( )

java.lang.Comparable

same as argument type

minimum value of expression across all non-null values

max( )

java.lang.Comparable

same as argument type

maximum value of expression across all non-null values

sum( )

java.lang.Number

java.math.BigDecimal

sum of expression across all non-null values

avg( )

java.lang.Number

java.math.BigDecimal

the average (arithmetic mean) of all non-null values

list( )

any

java.util.List

the aggregated list of all non-null values

median( )

java.lang.Number

java.math.BigDecimal

value such that the number of non-null values above and below it is the same ("middle" value, not necessarily same as average or mean)

stdev( )

java.lang.Number

java.math.BigDecimal

the statistical standard deviation of all non-null values

stdevp( )

java.lang.Number

java.math.BigDecimal

the statistical standard deviation for the population for all non-null values

var( )

java.lang.Number

java.math.BigDecimal

the statistical variance of all non-null values

varp( )

java.lang.Number

java.math.BigDecimal

the statistical variance for the population for all non-null values

agg( )

any

any

customizes the aggregation logic in and returns single value

is an implicit variable for aggregate function, it represents the grouped object and its record(e.g. ) could reference the data source by alias(e.g. )

Also, we could apply the aggregate functions for the whole GINQ result, i.e. no groupby clause is needed:

orderby is equivalent to SQL’s ORDER BY

is optional when sorting ascending order
is equivalent to SQL’s and applied by default. is equivalent to SQL’s .

limit is similar to the limit clause of MySQL, which could specify the offset (first argument) and size (second argument) for paginating, or just specify the only one argument as size

Nested GINQ

It’s recommended to use to restrict the count of sub-query result because will be thrown if more than one values returned

We could use as clause to name the sub-query result

Window Functions

Window can be defined by partitionby , orderby , rows and range :

0 used as bound of rows and range clause is equivalent to SQL’s CURRENT ROW , and negative means PRECEDING , positive means FOLLOWING

null used as the lower bound of rows and range clause is equivalent to SQL’s UNBOUNDED PRECEDING

null used as the upper bound of rows and range clause is equivalent to SQL’s UNBOUNDED FOLLOWING

Also, GINQ provides some built-in window functions:

Function Argument Type(s) Return Type Description

rowNumber()

java.lang.Long

number of the current row within its partition, counting from

rank()

java.lang.Long

rank of the current row with gaps

denseRank()

java.lang.Long

rank of the current row without gaps

percentRank()

java.math.BigDecimal

relative rank of the current row: (rank - 1) / (total rows - 1)

cumeDist()

java.math.BigDecimal

relative rank of the current row: (number of rows preceding or peer with current row) / (total rows)

ntile( )

java.lang.Long

java.lang.Long

bucket index ranging from to , dividing the partition as equally as possible

lead( [, [, ]])

any [, java.lang.Long [, same as type]]

same as type

returns evaluated at the row that is rows after the current row within the partition; if there is no such row, instead return (which must be of the same type as ). Both and are evaluated with respect to the current row. If omitted, defaults to and to

lag( [, [, ]])

any [, java.lang.Long [, same as type]]

same as type

returns evaluated at the row that is rows before the current row within the partition; if there is no such row, instead return (which must be of the same type as ). Both and are evaluated with respect to the current row. If omitted, defaults to and to

firstValue( )

any

same type as

returns evaluated at the row that is the first row of the window frame

lastValue( )

any

same type as

returns evaluated at the row that is the last row of the window frame

nthValue( , )

any, java.lang.Long

same type as

returns evaluated at the row that is the row of the window frame

count()

java.lang.Long

number of rows, similar to in SQL

count( )

any

java.lang.Long

number of rows for which the value of is not

min( )

java.lang.Comparable

same as argument type

minimum value of expression across all non-null values

max( )

java.lang.Comparable

same as argument type

maximum value of expression across all non-null values

sum( )

java.lang.Number

java.math.BigDecimal

sum of expression across all non-null values

avg( )

java.lang.Number

java.math.BigDecimal

the average (arithmetic mean) of all non-null values

median( )

java.lang.Number

java.math.BigDecimal

value such that the number of non-null values above and below it is the same ("middle" value, not necessarily same as average or mean)

stdev( )

java.lang.Number

java.math.BigDecimal

the statistical standard deviation of all non-null values

stdevp( )

java.lang.Number

java.math.BigDecimal

the statistical standard deviation for the population for all non-null values

var( )

java.lang.Number

java.math.BigDecimal

the statistical variance of all non-null values

varp( )

java.lang.Number

java.math.BigDecimal

the statistical variance for the population for all non-null values

agg( )

any

any

: customizes the aggregation logic in and returns single value

The parentheses around the window function is required.

The offset can be specified other than the default offset 1 :

The default value can be returned when the index specified by offset is out of window, e.g. 'NONE' :

_rn is the implicit variable representing row number for each record in the result set. It starts with 0

List comprehension is an elegant way to define and create lists based on existing lists:

is the abbreviation of

GINQ could be used as list comprehension in the loops directly:

This is like update statement in SQL

GINQ does not support with clause for now, but we could define a temporary variable to workaround:

case-when of SQL could be replaced with switch expression:

Parallel querying is especially efficient when querying big data sources. It is disabled by default, but we could enable it by hand:

As parallel querying will use a shared thread pool, the following code can release resources after all GINQ statements execution are completed, and it will wait util all tasks of threads are completed.

Once is issued, parallel querying can not work anymore.

The following code is equivalent to the above code, in other words, immediate is optional:

Shutdown without waiting tasks to complete:

For advanced users, you could customize GINQ behaviour by specifying your own target code generator. For example, we could specify the qualified class name org.apache.groovy.ginq.provider.collection.GinqAstWalker as the target code generator to generate GINQ method calls for querying collections, which is the default behaviour of GINQ:

GINQ optimizer is enabled by default for better performance. It will transform the GINQ AST to achieve better execution plan. We could disable it by hand:

GINQ Examples

link: the latest GINQ examples

Some examples in the above link require the latest SNAPSHOT version of Groovy to run.

3.11. Processing XML

3.11.1. parsing xml.

The most commonly used approach for parsing XML with Groovy is to use one of:

groovy.xml.XmlParser

groovy.xml.XmlSlurper

Both have the same approach to parse an XML. Both come with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others. For the next example we will use the parseText method. It parses an XML String and recursively converts it to a list or map of objects.

Parsing the XML an returning the root node as a GPathResult
Checking we’re using a GPathResult
Traversing the tree in a GPath style
Parsing the XML an returning the root node as a Node
Checking we’re using a Node
Traversing the tree in a GPath style

Let’s see the similarities between XMLParser and XMLSlurper first:

Both are based on SAX so they both are low memory footprint

Both can update/transform the XML

But they have key differences :

XmlSlurper evaluates the structure lazily. So if you update the xml you’ll have to evaluate the whole tree again.

XmlSlurper returns GPathResult instances when parsing XML

XmlParser returns Node objects when parsing XML

When to use one or the another?

There is a discussion at . The conclusions written here are based partially on this entry.

If you want to transform an existing document to another then XmlSlurper will be the choice

If you want to update and read at the same time then XmlParser is the choice.

The rationale behind this is that every time you create a node with XmlSlurper it won’t be available until you parse the document again with another XmlSlurper instance. Need to read just a few nodes XmlSlurper is for you ".

If you just have to read a few nodes XmlSlurper should be your choice, since it will not have to create a complete structure in memory"

In general both classes perform similar way. Even the way of using GPath expressions with them are the same (both use breadthFirst() and depthFirst() expressions). So I guess it depends on the write/read frequency.

There is another way of parsing XML documents with Groovy with the use of groovy.xml.dom.DOMCategory which is a category class which adds GPath style operations to Java’s DOM classes.

Java has in-built support for DOM processing of XML using classes representing the various parts of XML documents, e.g. , , , etc. For more information about these classes, refer to the respective JavaDocs.

Having an XML like the following:

You can parse it using groovy.xml.DOMBuilder and groovy.xml.dom.DOMCategory .

Parsing the XML
Creating scope to be able to use helper method calls

3.11.2. GPath

The most common way of querying XML in Groovy is using GPath :

GPath is a path expression language integrated into Groovy which allows parts of nested structured data to be identified. In this sense, it has similar aims and scope as XPath does for XML. The two main places where you use GPath expressions is when dealing with nested POJOs or when dealing with XML

It is similar to XPath expressions and you can use it not only with XML but also with POJO classes. As an example, you can specify a path to an object or element of interest:

a.b.c → for XML, yields all the <c> elements inside <b> inside <a>

a.b.c → all POJOs, yields the <c> properties for all the <b> properties of <a> (sort of like a.getB().getC() in JavaBeans)

For XML, you can also specify attributes, e.g.:

a["@href"] → the href attribute of all the a elements

a.'@href' → an alternative way of expressing this

a.@href → an alternative way of expressing this when using XmlSlurper

Let’s illustrate this with an example:

First thing we could do is to get a value using POJO’s notation. Let’s get the first book’s author’s name

First we parse the document with XmlSlurper and then we have to consider the returning value as the root of the XML document, so in this case is "response".

That’s why we start traversing the document from response and then value.books.book[0].author . Note that in XPath the node arrays starts in [1] instead of [0], but because GPath is Java-based it begins at index 0.

In the end we’ll have the instance of the author node and because we wanted the text inside that node we should be calling the text() method. The author node is an instance of GPathResult type and text() a method giving us the content of that node as a String.

When using GPath with an XML parsed with XmlSlurper we’ll have as a result a GPathResult object. GPathResult has many other convenient methods to convert the text inside a node to any other type such as:

toInteger()

toBigInteger()

…​

All these methods try to convert a String to the appropriate type.

If we were using an XML parsed with XmlParser we could be dealing with instances of type Node . But still all the actions applied to GPathResult in these examples could be applied to a Node as well. Creators of both parsers took into account GPath compatibility.

Next step is to get some values from a given node’s attribute. In the following sample we want to get the first book’s author’s id. We’ll be using two different approaches. Let’s see the code first:

Getting the first book node
Getting the book’s id attribute
Getting the book’s id attribute with
Getting the value as a String
Getting the value of the attribute as an

As you can see there are two types of notations to get attributes, the

direct notation with @nameoftheattribute

map notation using ['@nameoftheattribute']

Both of them are equally valid.

If you ever have used XPath, you may have used expressions like:

/following-sibling::othernode : Look for a node "othernode" in the same level

// : Look everywhere

More or less we have their counterparts in GPath with the shortcuts * (aka children() ) and ** (aka depthFirst() ).

The first example shows a simple use of * , which only iterates over the direct children of the node.

This test searches for any child nodes of the "books" node matching the given condition. In a bit more detail, the expression says: Look for any node with a tag name equal to 'book' having an id with a value of '2' directly under the 'books' node .

This operation roughly corresponds to the breadthFirst() method, except that it only stops at one level instead of continuing to the inner levels.

What if we would like to look for a given value without having to know exactly where it is. Let’s say that the only thing we know is the id of the author "Lewis Carroll" . How are we going to be able to find that book? Using ** is the solution:

** is the same as looking for something everywhere in the tree from this point down . In this case, we’ve used the method find(Closure cl) to find just the first occurrence.

What if we want to collect all book’s titles? That’s easy, just use findAll :

In the last two examples, ** is used as a shortcut for the depthFirst() method. It goes as far down the tree as it can while navigating down the tree from a given node. The breadthFirst() method finishes off all nodes on a given level before traversing down to the next level.

The following example shows the difference between these two methods:

In this example, we search for any nodes with an id attribute with value 2 or 3. There are both book and author nodes that match that criteria. The different traversal orders will find the same nodes in each case but in different orders corresponding to how the tree was traversed.

It is worth mentioning again that there are some useful methods converting a node’s value to an integer, float, etc. Those methods could be convenient when doing comparisons like this:

In this case the number 2 has been hardcoded but imagine that value could have come from any other source (database…​ etc.).

3.11.3. Creating XML

The most commonly used approach for creating XML with Groovy is to use a builder, i.e. one of:

groovy.xml.MarkupBuilder

groovy.xml.StreamingMarkupBuilder

Here is an example of using Groovy’s MarkupBuilder to create a new XML file:

Create an instance of
Start creating the XML tree
Create an instance of to traverse and test the generated XML

Let’s take a look a little bit closer:

We’re creating a reference string to compare against
The instance is used by to convert the xml representation to a String instance eventually
The call will create an XML node with a tag called and with content .
This time in order to create both attributes and node content you can create as many map entries as you like and finally add a value to set the node’s content
The value could be any , the value will be serialized to its representation.
A closure represents the children elements of a given node. Notice this time instead of using a String for the attribute we’re using a number.

Sometimes you may want to use a specific namespace in your xml documents:

Creating a node with a given namespace
Creating a registering the namespace to be able to test the XML we just created

What about having some more meaningful example. We may want to generate more elements, to have some logic when creating our XML:

Generating elements from a range
Using a conditional for creating a given element

Of course the instance of a builder can be passed as a parameter to refactor/modularize your code:

In this case we’ve created a Closure to handle the creation of a list of movies
Just using the function when necessary

The class groovy.xml.StreamingMarkupBuilder is a builder class for creating XML markup. This implementation uses a groovy.xml.streamingmarkupsupport.StreamingMarkupWriter to handle output.

Note that returns a instance that may be used to stream the markup to a Writer
We’re capturing the output in a String to parse it again and check the structure of the generated XML with .

The groovy.xml.MarkupBuilderHelper is, as its name reflects, a helper for groovy.xml.MarkupBuilder .

This helper normally can be accessed from within an instance of class groovy.xml.MarkupBuilder or an instance of groovy.xml.StreamingMarkupBuilder .

This helper could be handy in situations when you may want to:

Produce a comment in the output

Produce an XML processing instruction in the output

Produce an XML declaration in the output

Print data in the body of the current tag, escaping XML entities

Print data in the body of the current tag

In both MarkupBuilder and StreamingMarkupBuilder this helper is accessed by the property mkp :

Using to create a comment in the XML
Using to generate an escaped value
Checking both assumptions were true

Here is another example to show the use of mkp property accessible from within the bind method scope when using StreamingMarkupBuilder :

If we want to generate an escaped value for the name attribute with
Checking the values later on with

Suppose we have an existing XML document and we want to automate generation of the markup without having to type it all in? We just need to use org.codehaus.groovy.tools.xml.DOMToGroovy as shown in the following example:

Creating instance
Converts the XML to calls which are available in the output
Using variable to create the whole MarkupBuilder
Back to XML string

3.11.4. Manipulating XML

In this chapter you’ll see the different ways of adding / modifying / removing nodes using XmlSlurper or XmlParser . The xml we are going to be handling is the following:

The main difference between XmlSlurper and XmlParser is that when former creates the nodes they won’t be available until the document’s been evaluated again, so you should parse the transformed document again in order to be able to see the new nodes. So keep that in mind when choosing any of both approaches.

If you needed to see a node right after creating it then XmlParser should be your choice, but if you’re planning to do many changes to the XML and send the result to another process maybe XmlSlurper would be more efficient.

You can’t create a new node directly using the XmlSlurper instance, but you can with XmlParser . The way of creating a new node from XmlParser is through its method createNode(..)

The createNode() method receives the following parameters:

parent node (could be null)

The qualified name for the tag (In this case we only use the local part without any namespace). We’re using an instance of groovy.namespace.QName

A map with the tag’s attributes (None in this particular case)

Anyway you won’t normally be creating a node from the parser instance but from the parsed XML instance. That is from a Node or a GPathResult instance.

Take a look at the next example. We are parsing the xml with XmlParser and then creating a new node from the parsed document’s instance (Notice the method here is slightly different in the way it receives the parameters):

When using XmlSlurper , GPathResult instances don’t have createNode() method.

We know how to parse the document, add new nodes, now I want to change a given node’s content. Let’s start using XmlParser and Node . This example changes the first book information to actually another book.

When using replaceNode() the closure we pass as parameter should follow the same rules as if we were using groovy.xml.MarkupBuilder :

Here’s the same example using XmlSlurper :

Notice how using XmlSlurper we have to parse the transformed document again in order to find the created nodes. In this particular example could be a little bit annoying isn’t it?

Finally both parsers also use the same approach for adding a new attribute to a given attribute. This time again the difference is whether you want the new nodes to be available right away or not. First XmlParser :

And XmlSlurper :

When using XmlSlurper , adding a new attribute does not require you to perform a new evaluation.

Printing XML

Sometimes is useful to get not only the value of a given node but the node itself (for instance to add this node to another XML).

For that you can use groovy.xml.XmlUtil class. It has several static methods to serialize the xml fragment from several type of sources (Node, GPathResult, String…​)

3.12. Processing YAML

Groovy has an optional groovy-yaml module which provides support for converting between Groovy objects and YAML. The classes dedicated to YAML serialisation and parsing are found in the groovy.yaml package.

3.12.1. YamlSlurper

YamlSlurper is a class that parses YAML text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String .

The class comes with a bunch of overloaded parse methods plus some special methods such as parseText and others. For the next example we will use the parseText method. It parses a YAML String and recursively converts it to a list or map of objects. The other parse* methods are similar in that they return a YAML String but for different parameter types.

Notice the result is a plain map and can be handled like a normal Groovy object instance. YamlSlurper parses the given YAML as defined by the YAML Ain’t Markup Language (YAML™) .

As YamlSlurper is returning pure Groovy object instances without any special YAML classes in the back, its usage is transparent. In fact, YamlSlurper results conform to GPath expressions. GPath is a powerful expression language that is supported by multiple slurpers for different data formats ( XmlSlurper for XML being one example).

The following table gives an overview of the YAML types and the corresponding Groovy data types:

YAML Groovy

string

number

or

object

array

true

false

null

date

based on the date format

Whenever a value in YAML is , supplements it with the Groovy value. This is in contrast to other YAML parsers that represent a value with a library-provided singleton object.

Another way to create YAML from Groovy is to use YamlBuilder . The builder provide a DSL which allows to formulate an object graph which is then converted to YAML.

3.13. Processing TOML

Groovy has an optional groovy-toml module which provides support for converting between Groovy objects and TOML. The classes dedicated to TOML serialisation and parsing are found in the groovy.toml package.

3.13.1. TomlSlurper

TomlSlurper is a class that parses TOML text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String .

The class comes with a bunch of overloaded parse methods plus some special methods such as parseText and others. For the next example we will use the parseText method. It parses a TOML String and recursively converts it to a list or map of objects. The other parse* methods are similar in that they return a TOML String but for different parameter types.

Notice the result is a plain map and can be handled like a normal Groovy object instance. TomlSlurper parses the given TOML as defined by the Tom’s Obvious, Minimal Language .

As TomlSlurper is returning pure Groovy object instances without any special TOML classes in the back, its usage is transparent. In fact, TomlSlurper results conform to GPath expressions. GPath is a powerful expression language that is supported by multiple slurpers for different data formats ( XmlSlurper for XML being one example).

The following table gives an overview of the TOML types and the corresponding Groovy data types:

TOML Groovy

string

number

or

object

array

true

false

null

date

based on the date format

Whenever a value in TOML is , supplements it with the Groovy value. This is in contrast to other TOML parsers that represent a value with a library-provided singleton object.

Another way to create TOML from Groovy is to use TomlBuilder . The builder provide a DSL which allows to formulate an object graph which is then converted to TOML.

3.14. Groovy Contracts – design by contract support for Groovy

This module provides contract annotations that support the specification of class-invariants, pre- and post-conditions on Groovy classes and interfaces. Special support is provided so that post-conditions may refer to the old value of variables or to the result value associated with calling a method.

With GContracts in your class-path, contracts can be applied on a Groovy class or interface by using one of the assertions found in package org.gcontracts.annotations.

GContracts supports the following feature set:

definition of class invariants, pre- and post-conditions via @Invariant, @Requires and @Ensures

inheritance of class invariants, pre- and post-conditions of concrete predecessor classes

inheritance of class invariants, pre- and post-conditions in implemented interfaces

usage of old and result variable in post-condition assertions

assertion injection in Plain Old Groovy Objects (POGOs)

human-readable assertion messages, based on Groovy power asserts

enabling contracts at package- or class-level with @AssertionsEnabled

enable or disable contract checking with Java’s -ea and -da VM parameters

annotation contracts: a way to reuse reappearing contract elements in a project domain model

detection of circular assertion method calls

Currently, Groovy contracts supports 3 annotations: @Invariant, @Requires and @Ensures – all of them work as annotations with closures, where closures allow you to specify arbitrary code pieces as annotation parameters:

The example above specifies a class-invariant and methods with pre- and post-conditions. Note, that preconditions may reference method arguments and post-conditions have access to the method’s result with the result variable and old instance variables values with old.

Indeed, Groovy AST transformations change these assertion annotations into Java assertion statements (can be turned on and off with a JVM param) and inject them at appropriate places, e.g. class-invariants are used to check an object’s state before and after each method call.

Groovy integrates very well with Apache Ant thanks to AntBuilder .

3.16. The <groovy> Ant Task

Here we describe an Ant task for using Groovy from within an Ant build file. You may also be interested in Ant’s built-in task which supports Groovy and other languages, or which lets you write Ant build scripts in Groovy rather than XML.

Executes a series of Groovy statements from Apache Ant . Statements can either be read in from a resource or as direct text between the enclosing Groovy tags.

Assuming all the groovy jars you need are in my.classpath (this will be groovy-VERSION.jar , groovy-ant-VERSION.jar plus any modules and transitive dependencies you might be using) you will need to declare this task at some point in the build.xml prior to the groovy task being invoked.

You can simply place statements between the groovy tags like this:

Or you can supply the Groovy source script as a resource. You can specify the pathname using the src attribute like this:

Or as a nested fileset like this (though the fileset definition is expected to select just one file):

Or as a nested single element resource collection which could look like any of these:

You may also supply a filter chain like this:

You might need to use the contextClassLoader attribute (see below) if any of your modules load services via the classpath, e.g. groovy-json .

Attribute Description Required

src

File containing Groovy statements. The directory containing the file is added to the classpath.

Yes, unless statements enclosed within tags

classpath

The classpath to use.

No

classpathref

The classpath to use, given as reference to a PATH defined elsewhere.

No

output

Set the output file; defaults to the Ant log.

No

append

If enabled and output is to a file, append to existing file rather than overwrite. Defaults to false.

No

fork

If enabled the script will be executed in a forked JVM process (disabled by default).

No

scriptBaseClass

The name of the base class for scripts.

No

parameters

Generates metadata for reflection on method parameter names on JDK 8 and above. Defaults to false.

No

useGroovyShell

If enabled a new GroovyShell is used to run the script. Special variables won’t be available but you don’t need Ant in the classpath. Defaults to false.

No

includeAntRuntime

If enabled the system classpath will be included on the classpath when forking. Defaults to true.

No

stacktrace

If enabled a stacktrace will be reported if an error occurs during compilation. Defaults to false.

No

configScript

Sets the configuration script for the groovy compiler configuration.

No

contextClassLoader

If enabled, the contextClassLoader to be set with the classLoader of the shell used to run the script. Not used if fork is true.

No

3.16.4. Parameters specified as nested elements

Groovy’s classpath attribute is a PATH like structure and can also be set via a nested classpath element.

Arguments can be set via one or more nested <arg> elements using the standard Ant command line conventions .

A number of bindings are in scope for use within your Groovy statements.

Name Description

ant

an instance of that knows about the current ant project

project

the current ant project

properties

a of ant properties

target

the owning target that invoked this groovy script

task

the wrapping task, can access anything needed in

args

command line arguments, if any

Hello world, version 1:

Hello world, version 2:

List all xml files in the current directory:

List all xml files within a jar:

Run a script:

Find all Builder classes having an org.* package within a directory of jars:

Which might result in something like:

FileScanner version of above (with a slight variation on collecting the names):

Calling out to a web service from your Ant script:

Which will output the following (along with some informational messages):

Setting arguments:

3.17. The <groovyc> Ant Task

3.17.1. <groovyc>.

Compiles Groovy source files and, if joint compilation option is used, Java source files from Apache Ant .

Assuming the groovy jars are in groovy.libs , you will need to declare this task at some point in the build.xml prior to the groovyc task being invoked. Consider also adding any additional Groovy module jars, libraries and potentially transitive dependencies you might be using.

Attribute Description Required

srcdir

Location of the Groovy (and possibly Java) source files.

Yes

destdir

Location to store the class files.

Yes

classpath

The classpath to use.

No

classpathref

The classpath to use given as a path references.

No

sourcepath

The sourcepath to use.

No

sourcepathref

The sourcepath to use given as a path reference.

No

encoding

Encoding of source files.

No

verbose

Asks the compiler for verbose output; defaults to no.

No

includeAntRuntime

Whether to include the Ant run-time libraries in the classpath; defaults to yes.

No

includeJavaRuntime

Whether to include the default run-time libraries from the executing VM in the classpath; defaults to no.

No

includeDestClasses

This property controls whether to include the destination classes directory in the classpath given to the compiler. The default value is "true".

No

fork

Whether to execute groovyc using a spawned instance of the JVM; defaults to no.

No

memoryInitialSize

The initial size of the memory for the underlying VM, if using fork mode; ignored otherwise. Defaults to the standard VM memory setting. (Examples: 83886080, 81920k, or 80m)

No

memoryMaximumSize

The maximum size of the memory for the underlying VM, if using fork mode; ignored otherwise. Defaults to the standard VM memory setting. (Examples: 83886080, 81920k, or 80m)

No

failonerror

Indicates whether compilation errors will fail the build; defaults to true.

No

proceed

Inverse alias for .

No

listfiles

Indicates whether the source files to be compiled will be listed; defaults to no.

No

stacktrace

if true each compile error message will contain a stacktrace

No

indy

Enable compilation with the ``invoke dynamic'' support when using Groovy 2.0 and beyond and running on JDK 7

No

scriptBaseClass

Sets the base class for Groovy scripts

No

stubdir

Set the stub directory into which the Java source stub files should be generated. The directory need not exist and will not be deleted automatically - though its contents will be cleared unless 'keepStubs' is true. Ignored when forked.

No

keepStubs

Set the keepStubs flag. Defaults to false. Set to true for debugging. Ignored when forked.

No

forceLookupUnnamedFiles

The Groovyc Ant task is frequently used in the context of a build system that knows the complete list of source files to be compiled. In such a context, it is wasteful for the Groovy compiler to go searching the classpath when looking for source files and hence by default the Groovyc Ant task calls the compiler in a special mode with such searching turned off. If you wish the compiler to search for source files then you need to set this flag to true. Defaults to false.

No

configscript

Set the configuration file used to customize the compilation configuration.

No

parameters

Generates metadata for reflection on method parameter names on JDK 8 and above. Defaults to false.

No

previewFeatures

Enables the JEP preview features on JDK 12 and above. Defaults to false.

No

targetBytecode

Sets the bytecode compatibility level.

No

javahome

Sets the value to use, default is the current JDK’s home.

No

executable

Sets the name of the java executable to use when invoking the compiler in forked mode, ignored otherwise.

No

scriptExtension

Set the extension to use when searching for Groovy source files. Accepts extensions in the form *.groovy, .groovy or groovy.

No

updatedProperty

The property to set on compilation success. This property will not be set if the compilation fails, or if there are no files to compile.

No

errorProperty

The property to set on compilation failure. This property will be set if the compilation fails.

No

element kind Required Replaces Attribute

src

a path structure

Yes (unless srcdir is used)

srcdir

classpath

a path structure

No

classpath or classpathref

javac

javac task

No

N/A

For path structures see for example https://ant.apache.org/manual/using.html#path

For usages of the javac task see https://ant.apache.org/manual/Tasks/javac.html

The nested javac task behaves more or less as documented for the top-level javac task. srcdir , destdir , classpath , encoding and parameters for the nested javac task are taken from the enclosing groovyc task. If these attributes are specified then they are added, they do not replace. In fact, you should not attempt to overwrite the destination. Other attributes and nested elements are unaffected, for example fork , memoryMaximumSize , etc. may be used freely.

Joint compilation is enabled by using an embedded javac element, as shown in the following example:

More details about joint compilation can be found in the joint compilation section.

3.18. Template engines

Groovy supports multiple ways to generate text dynamically including GStrings , printf and MarkupBuilder just to name a few. In addition to these, there is a dedicated template framework which is well-suited to applications where the text to be generated follows the form of a static template.

The template framework in Groovy consists of a TemplateEngine abstract base class that engines must implement and a Template interface that the resulting templates they generate must implement.

Included with Groovy are several template engines:

SimpleTemplateEngine - for basic templates

StreamingTemplateEngine - functionally equivalent to SimpleTemplateEngine , but can handle strings larger than 64k

GStringTemplateEngine - stores the template as writeable closures (useful for streaming scenarios)

XmlTemplateEngine - works well when the template and output are valid XML

MarkupTemplateEngine - a very complete, optimized, template engine

3.18.3. SimpleTemplateEngine

Shown here is the SimpleTemplateEngine that allows you to use JSP-like scriptlets (see example below), script, and EL expressions in your template in order to generate parametrized text. Here is an example of using the system:

While it is generally not deemed good practice to mix processing logic in your template (or view), sometimes very simple logic can be useful. E.g. in the example above, we could change this:

to this (assuming we have set up a static import for capitalize inside the template):

If you happen to be embedding your template directly in your script (as we did above) you have to be careful about backslash escaping. Because the template string itself will be parsed by Groovy before it is passed to the templating framework, you have to escape any backslashes inside GString expressions or scriptlet 'code' that are entered as part of a Groovy program. E.g. if we wanted quotes around The Big Apple above, we would use:

Similarly, if we wanted a newline, we would use:

in any GString expression or scriptlet 'code' that appears inside a Groovy script. A normal “\n” is fine within the static template text itself or if the entire template itself is in an external template file. Similarly, to represent an actual backslash in your text you would need

in an external file or

in any GString expression or scriptlet 'code'. (Note: the necessity to have this extra slash may go away in a future version of Groovy if we can find an easy way to support such a change.)

The StreamingTemplateEngine engine is functionally equivalent to the SimpleTemplateEngine , but creates the template using writable closures making it more scalable for large templates. Specifically this template engine can handle strings larger than 64k.

It uses JSP style <% %> script and <%= %> expression syntax or GString style expressions. The variable 'out' is bound to the writer that the template is being written to.

Frequently, the template source will be a file but here we show a simple example providing the template as a string:

As an example of using the GStringTemplateEngine , here is the example above done again (with a few changes to show some other options). First we will store the template in a file this time:

Note that we used out instead of print to support the streaming nature of GStringTemplateEngine . Because we have the template in a separate file, there is no need to escape the backslashes. Here is how we call it:

and here is the output:

XmlTemplateEngine for use in templating scenarios where both the template source and the expected output are intended to be XML. Templates may use the normal ${expression} and $variable notations to insert an arbitrary expression into the template. In addition, support is also provided for special tags: <gsp:scriptlet> (for inserting code fragments) and <gsp:expression> (for code fragments which produce output).

Comments and processing instructions will be removed as part of processing and special XML characters such as < , > , " and ' will be escaped using the respective XML notation. The output will also be indented using standard XML pretty printing.

The xmlns namespace definition for gsp: tags will be removed but other namespace definitions will be preserved (but may change to an equivalent position within the XML tree).

Normally, the template source will be in a file but here is a simple example providing the XML template as a string:

This example will produce this output:

3.18.7. The MarkupTemplateEngine

This template engine is a template engine primarily aimed at generating XML-like markup (XML, XHTML, HTML5, …​), but that can be used to generate any text based content. Unlike traditional template engines, this one relies on a DSL that uses the builder syntax. Here is a sample template:

If you feed it with the following model:

It would be rendered as:

The key features of this template engine are:

a markup builder like syntax

templates are compiled into bytecode

fast rendering

optional type checking of the model

internationalization support

fragments/layouts

The template format

Templates consist of Groovy code. Let’s explore the first example more thoroughly:

renders the XML declaration string.
opens a tag
is a variable found in the , which is a list of instances
for each item, we create a tag with the attributes from the instance
closes the tag

As you can see, regular Groovy code can be used in the template. Here, we are calling each on a list (retrieved from the model), allowing us to render one car tag per entry.

In a similar fashion, rendering HTML code is as simple as this:

renders the HTML doctype special tag
opens the tag with an attribute
opens the tag
renders a tag with one attribute
renders the tag
closes the tag
opens the tag
renders a tag
closes the tag
closes the tag

The output is straightforward:

With some , you can have the output pretty printed, with newlines and indent automatically added.

In the previous example, the doctype declaration was rendered using the yieldUnescaped method. We have also seen the xmlDeclaration method. The template engine provides several support methods that will help you render contents appropriately:

Method Description Example

yield

Renders contents, but escapes it before rendering

:

:

yieldUnescaped

Renders raw contents. The argument is rendered as is, without escaping.

:

:

xmlDeclaration

Renders an XML declaration String. If the encoding is specified in the configuration, it is written in the declaration.

:

:

is not null:

:

comment

Renders raw contents inside an XML comment

:

:

newLine

Renders a new line. See also and .

:

:

pi

Renders an XML processing instruction.

:

:

tryEscape

Returns an escaped string for an object, if it is a (or any type derived from ). Otherwise returns the object itself.

:

:

The MarkupTemplateEngine supports inclusion of contents from another file. Included contents may be:

another template

raw contents

contents to be escaped

Including another template can be done using:

Including a file as raw contents, without escaping it, can be done like this:

Eventually, inclusion of text that should be escaped before rendering can be done using:

Alternatively, you can use the following helper methods instead:

includeGroovy(<name>) to include another template

includeEscaped(<name>) to include another file with escaping

includeUnescaped(<name>) to include another file without escaping

Calling those methods instead of the include xxx: syntax can be useful if the name of the file to be included is dynamic (stored in a variable for example). Files to be included (independently of their type, template or text) are found on classpath . This is one of the reasons why the MarkupTemplateEngine takes an optional ClassLoader as constructor argument (the other reason being that you can include code referencing other classes in a template).

If you don’t want your templates to be on classpath, the MarkupTemplateEngine accepts a convenient constructor that lets you define the directory where templates are to be found.

Fragments are nested templates. They can be used to provide improved composition in a single template. A fragment consists of a string, the inner template, and a model, used to render this template. Consider the following template:

The fragment element creates a nested template, and renders it with a model which is specific to this template. Here, we have the li(line) fragment, where line is bound to it . Since it corresponds to the iteration of pages , we will generate a single li element for each page in our model:

Fragments are interesting to factorize template elements. They come at the price of the compilation of a fragment per template, and they cannot be externalized.

Layouts, unlike fragments, refer to other templates. They can be used to compose templates and share common structures. This is often interesting if you have, for example, a common HTML page setup, and that you only want to replace the body. This can be done easily with a layout . First of all, you need to create a layout template:

the variable (inside the title tag) is a layout variable
the call will render the body

Then what you need is a template that includes the layout:

use the layout file
set the variable
set the

As you can see, bodyContents will be rendered inside the layout, thanks to the bodyContents() call in the layout file. As a result, the template will be rendered as this:

The call to the contents method is used to tell the template engine that the block of code is in fact a specification of a template, instead of a helper function to be rendered directly. If you don’t add contents before your specification, then the contents would be rendered, but you would also see a random string generated, corresponding to the result value of the block.

Layouts are a powerful way to share common elements across multiple templates, without having to rewrite everything or use includes.

Layouts use, by default, a model which is independent from the model of the page where they are used. It is however possible to make them inherit from the parent model. Imagine that the model is defined like this:

and the following template:

note the use of to enable model inheritance

then it is not necessary to pass the title value to the layout as in the previous example . The result will be:

But it is also possible to override a value from the parent model:

means inherit from the parent model
but is overridden

then the output will be:

Rendering contents

On the server side, rendering templates require an instance of groovy.text.markup.MarkupTemplateEngine and a groovy.text.markup.TemplateConfiguration :

creates a template configuration
creates a template engine with this configuration
creates a template instance from a
creates a model to be used in the template
bind the model to the template instance
render output

There are several possible options to parse templates:

from a String , using createTemplate(String)

from a Reader , using createTemplate(Reader)

from a URL , using createTemplate(URL)

given a template name, using createTemplateByPath(String)

The last version should in general be preferred:

The behavior of the engine can be tweaked with several configuration options accessible through the TemplateConfiguration class:

Option Default value Description Example

declarationEncoding

null

Determines the value of the encoding to be written when is called. It does influence the writer you are using as output.

:

:

is not null:

:

expandEmptyElements

false

If true, empty tags are rendered in their expanded form.

:

:

is true:

:

useDoubleQuotes

false

If true, use double quotes for attributes instead of simple quotes

:

:

is true:

:

newLineString

System default (system property )

Allows to choose what string is used when a new line is rendered

:

:

:

autoEscape

false

If true, variables from models are automatically escaped before rendering.

autoIndent

false

If true, performs automatic indentation after new lines

autoIndentString

four (4) spaces

The string to be used as indent.

autoNewLine

false

If true, performs automatic insertion of new lines

baseTemplateClass

Sets the super class of compiled templates. This can be used to provide application specific templates.

locale

Default locale

Sets the default locale for templates.

Once the template engine has been created, it is to change the configuration.

By default, the template engine will render output without any specific formatting. Some configuration options can improve the situation:

autoIndent is responsible for auto-indenting after a new line is inserted

autoNewLine is responsible for automatically inserting new lines based on the original formatting of the template source

In general, it is recommended to set both autoIndent and autoNewLine to true if you want human-readable, pretty printed, output:

Using the following template:

The output will now be:

We can slightly change the template so that the title instruction is found on the same line as the head one:

And the output will reflect that:

New lines are only inserted where curly braces for tags are found, and the insertion corresponds to where the nested content is found. This means that tags in the body of another tag will not trigger new lines unless they use curly braces themselves:

a new line is inserted because is not on the same line as
no new line is inserted, because we’re on the same depth as the previous tag
we can force rendering of a new line by explicitly calling
and this tag will be rendered on a separate line

This time, the output will be:

By default, the renderer uses four(4) spaces as indent, but you can change it by setting the TemplateConfiguration#autoIndentString property.

By default, contents which is read from the model is rendered as is . If this contents comes from user input, it can be sensible, and you might want to escape it by default, for example to avoid XSS injection. For that, the template configuration provides an option which will automatically escape objects from the model, as long as they inherit from CharSequence (typically, `String`s).

Let’s imagine the following setup:

Then you wouldn’t want the HTML from unsafeContents to be rendered as is, because of potential security issues:

Automatic escaping will fix this:

And now the output is properly escaped:

Note that using automatic escaping doesn’t prevent you from including unescaped contents from the model. To do this, your template should then explicitly mention that a model variable should not be escaped by prefixing it with unescaped. , like in this example:

Common gotchas

Say that you want to generate a <p> tag which contains a string containing markup:

and generates:

Can’t this be written shorter? A naive alternative would be:

but the result will not look as expected:

The reason is that the markup template engine is a streaming engine. In the original version, the first yield call generates a string which is streamed to the output, then the a link is generated and streamed, and then the last yield call is streamed, leading in an execution in order . But with the string version above, the order of execution is different:

the yield call requires an argument, a string

that arguments need to be evaluated before the yield call is generated

so evaluating the string leads to an execution of the a(href:…​) call before yield is itself called. This is not what you want to do. Instead, you want to generate a string which contains markup, which is then passed to the yield call. This can be done this way:

Note the stringOf call, which basically tells the markup template engine that the underlying markup needs to be rendered separately and exported as a string. Note that for simple expressions, stringOf can be replaced by an alternate tag notation that starts with a dollar sign:

It is worth noting that using or the special notation triggers the creation of a distinct string writer which is then used to render the markup. It is slower than using the version with calls to which perform direct streaming of the markup instead.

The template engine has native support for internationalization. For that, when you create the TemplateConfiguration , you can provide a Locale which is the default locale to be used for templates. Each template may have different versions, one for each locale. The name of the template makes the difference:

file.tpl : default template file

file_fr_FR.tpl : french version of the template

file_en_US.tpl : american english version of the template

When a template is rendered or included, then:

if the template name or include name explicitly sets a locale, the specific version is included, or the default version if not found

if the template name doesn’t include a locale, the version for the TemplateConfiguration locale is used, or the default version if not found

For example, imagine the default locale is set to Locale.ENGLISH and that the main template includes:

then the template is rendered using the specific template:

Using an include without specifying a locale will make the template engine look for a template with the configured locale, and if not, fallback to the default, like here:

However, changing the default locale of the template engine to Locale.FRANCE will change the output, because the template engine will now look for a file with the fr_FR locale:

This strategy lets you translate your templates one by one, by relying on default templates, for which no locale is set in the file name.

By default, templates created inherit the groovy.text.markup.BaseTemplate class. It may be interesting for an application to provide a different template class, for example to provide additional helper methods which are aware of the application, or customized rendering primitives (for HTML, for example).

The template engine provides this ability by setting an alternative baseTemplateClass in the TemplateConfiguration :

The custom base class has to extend BaseClass like in this example:

This example shows a class which provides an additional method named hasModule , which can then be used directly in the template:

Type checked templates

Even if templates are not type checked, they are statically compiled. This means that once the templates are compiled, performance should be very good. For some applications, it might be good to make sure that templates are valid before they are actually rendered. This means failing template compilation, for example, if a method on a model variable doesn’t exist.

The MarkupTemplateEngine provides such a facility. Templates can be optionally type checked. For that, the developer must provide additional information at template creation time, which is the types of the variables found in the model. Imagine a model exposing a list of pages, where a page is defined as:

Then a list of pages can be exposed in the model, like this:

A template can use it easily:

iterate on pages from the model
is valid
is (should be )

Without type checking, the compilation of the template succeeds, because the template engine doesn’t know about the model until a page is actually rendered. This means that the problem would only surface at runtime, once the page is rendered:

In some situations, this can be complicated to sort out or even notice. By declaring the type of the pages to the template engine, we’re now capable of failing at compile time:

create a map which will hold the model types
declare the type of the variables (note the use of a string for the type)
use instead of

This time, when the template is compiled at the last line, an error occurs:

This means that you don’t need to wait for the page to be rendered to see an error. The use of createTypeCheckedModelTemplate is mandatory.

Alternatively, if the developer is also the one who writes the templates, it is possible to declare the types of the expected variables directly in the template. In this case, even if you call createTemplate , it will be type checked:

types need to be declared in the header
declare one variable per object in the model

An additional interest of using type checked models is that performance should improve. By telling the type checker what are the expected types, you also let the compiler generate optimized code for that, so if you are looking for the best performance, consider using type checked templates.

Also, there are other templating solutions that can be used along with Groovy, such as FreeMarker , Velocity , StringTemplate and others.

3.19. Servlet support

You can write (Java) Servlets in Groovy (called Groovlets).

There is also a GroovyServlet .

This feature will automatically compile your .groovy source files, turn them into bytecode, load the Class and cache it until you change the source file.

Here’s a simple example to show you the kind of things you can do from a Groovlet.

Notice the use of implicit variables to access the session, output and request. Also notice that this is more like a script as it does not have a class wrapper.

Or, do the same thing using MarkupBuilder:

The following variables are ready for use in Groovlets:

variable name bound to note

request

ServletRequest

response

ServletResponse

context

ServletContext

application

ServletContext

session

getSession(false)

params

headers

out

response.getWriter()

sout

response.getOutputStream()

html

new MarkupBuilder(out)

json

new StreamingJsonBuilder(out)

The session variable is only set, if there was already a session object. See the if (session == null) checks in the examples above.

These variables cannot be re-assigned inside a Groovlet . They are bound on first access, allowing to e.g. calling methods on the response object before using out .

Add the following to your web.xml :

Then put the required groovy jar files into WEB-INF/lib .

Now put the .groovy files in, say, the root directory (i.e. where you would put your html files). The GroovyServlet takes care of compiling the .groovy files.

So for example using tomcat you could edit tomcat/conf/server.xml like this:

Then access it with http://localhost:8080/groovy/hello.groovy

3.20. Integrating Groovy in a Java application

3.20.1. groovy integration mechanisms.

The Groovy language proposes several ways to integrate itself into applications (Java or even Groovy) at runtime, from the most basic, simple code execution to the most complete, integrating caching and compiler customization.

All the examples written in this section are using Groovy, but the same integration mechanisms can be used from Java.

The groovy.util.Eval class is the simplest way to execute Groovy dynamically at runtime. This can be done by calling the me method:

Eval supports multiple variants that accept parameters for simple evaluation:

Simple evaluation with one bound parameter named
Same evaluation, with a custom bound parameter named
Simple evaluation with two bound parameters named and
Simple evaluation with three bound parameters named , and

The Eval class makes it very easy to evaluate simple scripts, but doesn’t scale: there is no caching of the script, and it isn’t meant to evaluate more than one-liners.

GroovyShell

The groovy.lang.GroovyShell class is the preferred way to evaluate scripts with the ability to cache the resulting script instance. Although the Eval class returns the result of the execution of the compiled script, the GroovyShell class offers more options.

create a new instance
can be used as with direct execution of the code
can read from multiple sources ( , , , )
can defer execution of the script. returns a instance
defines a method

It is possible to share data between the application and the script using a groovy.lang.Binding :

create a new that will contain shared data
create a using this shared data
add a string to the binding
add a date to the binding (you are not limited to simple types)
evaluate the script

Note that it is also possible to write from the script into the binding:

create a new instance
create a new using that shared data
use an variable to store the result into the binding
read the result from the caller

It is important to understand that you need to use an undeclared variable if you want to write into the binding. Using def or an explicit type like in the example below would fail because you would then create a local variable :

You must be very careful when using shared data in a multithreaded environment. The instance that you pass to is thread safe, and shared by all scripts.

It is possible to work around the shared instance of Binding by leveraging the Script instance which is returned by parse :

will store the variable inside
will store the variable inside

However, you must be aware that you are still sharing the same instance of a script. So this technique cannot be used if you have two threads working on the same script. In that case, you must make sure of creating two distinct script instances:

create an instance of script for thread 1
create an instance of script for thread 2
assign first binding to script 1
assign second binding to script 2
start first script in a separate thread
start second script in a separate thread
wait for completion

In case you need thread safety like here, it is more advisable to use the GroovyClassLoader directly instead.

We have seen that the parse method returns an instance of groovy.lang.Script , but it is possible to use a custom class, given that it extends Script itself. It can be used to provide additional behavior to the script like in the example below:

The custom class defines a property called name and a new method called greet . This class can be used as the script base class by using a custom configuration:

create a instance
instruct it to use as the base class for scripts
then use the compiler configuration when you create the shell
the script now has access to the new method
You are not limited to the sole configuration. You can use any of the compiler configuration tweaks, including the .

In the previous section , we have shown that GroovyShell was an easy tool to execute scripts, but it makes it complicated to compile anything but scripts. Internally, it makes use of the groovy.lang.GroovyClassLoader , which is at the heart of the compilation and loading of classes at runtime.

By leveraging the GroovyClassLoader instead of GroovyShell , you will be able to load classes, instead of instances of scripts:

create a new
will return an instance of
you can check that the class which is returns is really the one defined in the script
and you can create a new instance of the class, which is not a script
then call any method on it
A GroovyClassLoader keeps a reference of all the classes it created, so it is easy to create a memory leak. In particular, if you execute the same script twice, if it is a String, then you obtain two distinct classes!
dynamically create a class named "Foo"
create an identical looking class, using a separate call
make sure both classes have the same name
but they are actually different!

The reason is that a GroovyClassLoader doesn’t keep track of the source text. If you want to have the same instance, then the source must be a file, like in this example:

parse a class from a
parse a class from a distinct file instance, but pointing to the same physical file
make sure our classes have the same name
but now, they are the same instance

Using a File as input, the GroovyClassLoader is capable of caching the generated class file, which avoids creating multiple classes at runtime for the same source.

The groovy.util.GroovyScriptEngine class provides a flexible foundation for applications which rely on script reloading and script dependencies. While GroovyShell focuses on standalone Script s and GroovyClassLoader handles dynamic compilation and loading of any Groovy class, the GroovyScriptEngine will add a layer on top of GroovyClassLoader to handle both script dependencies and reloading.

To illustrate this, we will create a script engine and execute code in an infinite loop. First of all, you need to create a directory with the following script inside:

then you can execute this code using a GroovyScriptEngine :

create a script engine which will look for sources into our source directory
execute the script, which will return an instance of
print the greeting message

At this point, you should see a message printed every second:

Without interrupting the script execution, now replace the contents of the ReloadingTest file with:

And the message should change to:

But it is also possible to have a dependency on another script. To illustrate this, create the following file into the same directory, without interrupting the executing script:

and update the ReloadingTest script like this:

And this time, the message should change to:

And as a last test, you can update the Dependency.groovy file without touching the ReloadingTest file:

And you should observe that the dependent file was reloaded:

Ultimately, it is possible to perform more operations during compilation by relying directly on the org.codehaus.groovy.control.CompilationUnit class. This class is responsible for determining the various steps of compilation and would let you introduce new steps or even stop compilation at various phases. This is for example how stub generation is done, for the joint compiler.

However, overriding CompilationUnit is not recommended and should only be done if no other standard solution works.

JSR-223 is a standard API for calling scripting frameworks in Java. It is available since Java 6 and aims at providing a common framework for calling multiple languages from Java. Groovy provides its own richer integration mechanisms, and if you don’t plan to use multiple languages in the same application, it is recommended that you use the Groovy integration mechanisms instead of the limited JSR-223 API.

Here is how you need to initialize the JSR-223 engine to talk to Groovy from Java:

Then you can execute Groovy scripts easily:

It is also possible to share variables:

This next example illustrates calling an invokable function:

The engine keeps per default hard references to the script functions. To change this you should set an engine level scoped attribute to the script context of the name #jsr223.groovy.engine.keep.globals with a String being phantom to use phantom references, weak to use weak references or soft to use soft references - casing is ignored. Any other string will cause the use of hard references.

3.21. Domain-Specific Languages

Groovy lets you omit parentheses around the arguments of a method call for top-level statements. "command chain" feature extends this by allowing us to chain such parentheses-free method calls, requiring neither parentheses around arguments, nor dots between the chained calls. The general idea is that a call like a b c d will actually be equivalent to a(b).c(d) . This also works with multiple arguments, closure arguments, and even named arguments. Furthermore, such command chains can also appear on the right-hand side of assignments. Let’s have a look at some examples supported by this new syntax:

It is also possible to use methods in the chain which take no arguments, but in that case, the parentheses are needed:

If your command chain contains an odd number of elements, the chain will be composed of method / arguments, and will finish by a final property access:

This command chain approach opens up interesting possibilities in terms of the much wider range of DSLs which can now be written in Groovy.

The above examples illustrate using a command chain based DSL but not how to create one. There are various strategies that you can use, but to illustrate creating such a DSL, we will show a couple of examples - first using maps and Closures:

As a second example, consider how you might write a DSL for simplifying one of your existing APIs. Maybe you need to put this code in front of customers, business analysts or testers who might be not hard-core Java developers. We’ll use the Splitter from the Google Guava libraries project as it already has a nice Fluent API. Here is how we might use it out of the box:

It reads fairly well for a Java developer but if that is not your target audience or you have many such statements to write, it could be considered a little verbose. Again, there are many options for writing a DSL. We’ll keep it simple with Maps and Closures. We’ll first write a helper method:

now instead of this line from our original example:

we can write this:

Various operators in Groovy are mapped onto regular method calls on objects.

This allows you to provide your own Java or Groovy objects which can take advantage of operator overloading. The following table describes the operators supported in Groovy and the methods they map to.

Operator Method

a.plus(b)

a.minus(b)

a.multiply(b)

a.power(b)

a.div(b)

a.mod(b)

a.or(b)

a.and(b)

a.xor(b)

or

a.next()

or

a.previous()

a.getAt(b)

a.putAt(b, c)

a.leftShift(b)

a.rightShift(b)

a.rightShiftUnsigned(b)

b.isCase(a)

a.asBoolean()

a.bitwiseNegate()

a.negative()

a.positive()

a.asType(b)

a.equals(b)

! a.equals(b)

a.compareTo(b)

a.compareTo(b) > 0

a.compareTo(b) >= 0

a.compareTo(b) < 0

a.compareTo(b) <= 0

3.21.3. Script base classes

Groovy scripts are always compiled to classes. For example, a script as simple as:

is compiled to a class extending the abstract groovy.lang.Script class. This class contains a single abstract method called run . When a script is compiled, then its body will become the run method, while the other methods found in the script are found in the implementing class. The Script class provides base support for integration with your application through the Binding object, as illustrated in this example:

a binding is used to share data between the script and the calling class
a can be used with this binding
input variables are set from the calling class inside the binding
then the script is evaluated
and the variable has been "exported" into the binding

This is a very practical way to share data between the caller and the script, however it may be insufficient or not practical in some cases. For that purpose, Groovy allows you to set your own base script class. A base script class has to extend groovy.lang.Script and be a single abstract method type:

Then the custom script base class can be declared in the compiler configuration, for example:

create a custom compiler configuration
set the base script class to our custom base script class
then create a using that configuration
the script will then extend the base script class, giving direct access to the property and method

As an alternative, it is also possible to use the @BaseScript annotation directly into a script:

where @BaseScript should annotate a variable which type is the class of the base script. Alternatively, you can set the base script class as a member of the @BaseScript annotation itself:

We have seen that the base script class is a single abstract method type that needs to implement the run method. The run method is executed by the script engine automatically. In some circumstances it may be interesting to have a base class which implements the run method, but provides an alternative abstract method to be used for the script body. For example, the base script run method might perform some initialization before the run method is executed. This is possible by doing this:

the base script class should define one (and only one) abstract method
the method can be overridden and perform a task before executing the script body
calls the abstract method which will delegate to the user script
then it can return something else than the value from the script

If you execute this code:

Then you will see that the script is executed, but the result of the evaluation is 1 as returned by the run method of the base class. It is even clearer if you use parse instead of evaluate , because it would allow you to execute the run method several times on the same script instance:

In Groovy number types are considered equal to any other types. As such, it is possible to enhance numbers by adding properties or methods to them. This can be very handy when dealing with measurable quantities for example. Details about how existing classes can be enhanced in Groovy are found in the extension modules section or the categories section.

An illustration of this can be found in Groovy using the TimeCategory :

using the , a property is added to the class
similarly, the method returns a which can be used in calculus

Categories are lexically bound, making them a great fit for internal DSLs.

3.21.5. @DelegatesTo

@groovy.lang.DelegatesTo is a documentation and compile-time annotation aimed at:

documenting APIs that use closures as arguments

providing type information for the static type checker and compiler

The Groovy language is a platform of choice for building DSLs. Using closures, it’s quite easy to create custom control structures, as well as it is simple to create builders. Imagine that you have the following code:

One way of implementing this is using the builder strategy, which implies a method, named email  which accepts a closure as an argument. The method may delegate subsequent calls to an object that implements the  from ,  to ,  subject and  body methods. Again,  body is a method which accepts a closure as an argument and that uses the builder strategy.

Implementing such a builder is usually done the following way:

the EmailSpec class implements the  from ,  to , … methods. By calling  rehydrate , we’re creating a copy of the closure for which we set the  delegate ,  owner and  thisObject values. Setting the owner and the this object is not very important here since we will use the DELEGATE_ONLY strategy which says that the method calls will be resolved only against the delegate of the closure.

The EmailSpec class has itself a body method accepting a closure that is cloned and executed. This is what we call the builder pattern in Groovy.

One of the problems with the code that we’ve shown is that the user of the email method doesn’t have any information about the methods that he’s allowed to call inside the closure. The only possible information is from the method documentation. There are two issues with this: first of all, documentation is not always written, and if it is, it’s not always available (javadoc not downloaded, for example). Second, it doesn’t help IDEs. What would be really interesting, here, is for IDEs to help the developer by suggesting, once they are in the closure body, methods that exist on the email class.

Moreover, if the user calls a method in the closure which is not defined by the  EmailSpec class, the IDE should at least issue a warning (because it’s very likely that it will break at runtime).

One more problem with the code above is that it is not compatible with static type checking. Type checking would let the user know if a method call is authorized at compile time instead of runtime, but if you try to perform type checking on this code:

Then the type checker will know that there’s an  email method accepting a  Closure , but it will complain about every method call  inside the closure, because  from , for example, is not a method which is defined in the class. Indeed, it’s defined in the  EmailSpec class and it has absolutely no hint to help it knowing that the closure delegate will, at runtime, be of type  EmailSpec :

will fail compilation with errors like this one:

For those reasons, Groovy 2.1 introduced a new annotation named  @DelegatesTo . The goal of this annotation is to solve both the documentation issue, that will let your IDE know about the expected methods in the closure body, and it will also solve the type checking issue, by giving hints to the compiler about what are the potential receivers of method calls in the closure body.

The idea is to annotate the  Closure parameter of the  email method:

What we’ve done here is telling the compiler (or the IDE) that when the method will be called with a closure, the delegate of this closure will be set to an object of type  email . But there is still a problem: the default delegation strategy is not the one which is used in our method. So we will give more information and tell the compiler (or the IDE) that the delegation strategy is also changed:

Now, both the IDE and the type checker (if you are using @TypeChecked ) will be aware of the delegate and the delegation strategy. This is very nice because it will both allow the IDE to provide smart completion, but it will also remove errors at compile time that exist only because the behaviour of the program is normally only known at runtime!

The following code will now pass compilation:

DelegatesTo modes

@DelegatesTo supports multiple modes that we will describe with examples in this section.

In this mode, the only mandatory parameter is the  value which says to which class we delegate calls. Nothing more. We’re telling the compiler that the type of the delegate will  always be of the type documented by  @DelegatesTo (note that it can be a subclass, but if it is, the methods defined by the subclass will not be visible to the type checker).

In this mode, you must specify both the delegate class  and a delegation strategy. This must be used if the closure will not be called with the default delegation strategy, which is  Closure.OWNER_FIRST .

In this variant, we will tell the compiler that we are delegating to another parameter of the method. Take the following code:

Here, the delegate which will be used is  not created inside the  exec method. In fact, we take an argument of the method and delegate to it. Usage may look like this:

Each of the method calls are delegated to the  email parameter. This is a widely used pattern which is also supported by  @DelegatesTo using a companion annotation:

A closure is annotated with  @DelegatesTo , but this time, without specifying any class. Instead, we’re annotating another parameter with  @DelegatesTo.Target . The type of the delegate is then determined at compile time. One could think that we are using the parameter type, which in this case is  Object but this is not true. Take this code:

Remember that this works out of the box  without having to annotate with  @DelegatesTo . However, to make the IDE aware of the delegate type, or the  type checker aware of it, we need to add  @DelegatesTo . And in this case, it will know that the  Greeter variable is of type  Greeter , so it will not report errors on the  sayHello method  even if the exec method doesn’t explicitly define the target as of type Greeter . This is a very powerful feature, because it prevents you from writing multiple versions of the same  exec method for different receiver types!

In this mode, the  @DelegatesTo annotation also supports the  strategy parameter that we’ve described upper.

In the previous example, the  exec method accepted only one closure, but you may have methods that take multiple closures:

Then nothing prevents you from annotating each closure with  @DelegatesTo :

But more importantly, if you have multiple closures  and multiple arguments, you can use several targets:

At this point, you may wonder why we don’t use the parameter names as references. The reason is that the information (the parameter name) is not always available (it’s a debug-only information), so it’s a limitation of the JVM.

In some situations, it is interesting to instruct the IDE or the compiler that the delegate type will not be a parameter but a generic type. Imagine a configurator that runs on a list of elements:

Then this method can be called with any list like this:

To let the type checker and the IDE know that the configure method calls the closure on each element of the list, you need to use @DelegatesTo differently:

@DelegatesTo takes an optional genericTypeIndex argument that tells what is the index of the generic type that will be used as the delegate type. This must be used in conjunction with @DelegatesTo.Target and the index starts at 0. In the example above, that means that the delegate type is resolved against List<T> , and since the generic type at index 0 is T and inferred as a Realm , the type checker infers that the delegate type will be of type Realm .

We’re using a instead of a placeholder ( ) because of JVM limitations.

It is possible that none of the options above can represent the type you want to delegate to. For example, let’s define a mapper class which is parametrized with an object and defines a map method which returns an object of another type:

The mapper class takes two generic type arguments: the source type and the target type
The source object is stored in a final field
The method asks to convert the source object to a target object

As you can see, the method signature from map does not give any information about what object will be manipulated by the closure. Reading the method body, we know that it will be the value which is of type T , but T is not found in the method signature, so we are facing a case where none of the available options for @DelegatesTo is suitable. For example, if we try to statically compile this code:

Then the compiler will fail with:

In that case, you can use the type member of the @DelegatesTo annotation to reference T as a type token:

The annotation references a generic type which is not found in the method signature

Note that you are not limited to generic type tokens. The type member can be used to represent complex types, such as List<T> or Map<T,List<U>> . The reason why you should use that in last resort is that the type is only checked when the type checker finds usage of @DelegatesTo , not when the annotated method itself is compiled. This means that type safety is only ensured at the call site. Additionally, compilation will be slower (though probably unnoticeable for most cases).

3.21.6. Compilation customizers

Whether you are using  groovyc to compile classes or a  GroovyShell , for example, to execute scripts, under the hood, a compiler configuration is used. This configuration holds information like the source encoding or the classpath but it can also be used to perform more operations like adding imports by default, applying AST transformations transparently or disabling global AST transformations.

The goal of compilation customizers is to make those common tasks easy to implement. For that, the  CompilerConfiguration class is the entry point. The general schema will always be based on the following code:

Compilation customizers must extend the  org.codehaus.groovy.control.customizers.CompilationCustomizer class. A customizer works:

on a specific compilation phase

on  every class node being compiled

You can implement your own compilation customizer but Groovy includes some of the most common operations.

Using this compilation customizer, your code will have imports added transparently. This is in particular useful for scripts implementing a DSL where you want to avoid users from having to write imports. The import customizer will let you add all the variants of imports the Groovy language allows, that is:

class imports, optionally aliased

star imports

static imports, optionally aliased

static star imports

A detailed description of all shortcuts can be found in org.codehaus.groovy.control.customizers.ImportCustomizer

The AST transformation customizer is meant to apply AST transformations transparently. Unlike global AST transformations that apply on every class being compiled as long as the transform is found on classpath (which has drawbacks like increasing the compilation time or side effects due to transformations applied where they should not), the customizer will allow you to selectively apply a transform only for specific scripts or classes.

As an example, let’s say you want to be able to use  @Log in a script. The problem is that  @Log is normally applied on a class node and a script, by definition, doesn’t require one. But implementation wise, scripts are classes, it’s just that you cannot annotate this implicit class node with  @Log . Using the AST customizer, you have a workaround to do it:

That’s all! Internally, the  @Log AST transformation is applied to every class node in the compilation unit. This means that it will be applied to the script, but also to classes defined within the script.

If the AST transformation that you are using accepts parameters, you can use parameters in the constructor too:

As the AST transformation customizers works with objects instead of AST nodes, not all values can be converted to AST transformation parameters. For example, primitive types are converted to  ConstantExpression (that is LOGGER is converted to  new ConstantExpression('LOGGER') , but if your AST transformation takes a closure as an argument, then you have to give it a  ClosureExpression , like in the following example:

For a complete list of options, please refer to org.codehaus.groovy.control.customizers.ASTTransformationCustomizer

This customizer will allow the developer of a DSL to restrict the grammar of the language, for example, to prevent users from using particular constructs. It is only ``secure'' in that one aspect, i.e. limiting the allowable constructs within a DSL. It does  not replace a security manager which might additionally be needed as an orthogonal aspect of overall security. The only reason for it to exist is to limit the expressiveness of the language. This customizer only works at the AST (abstract syntax tree) level, not at runtime! It can be strange at first glance, but it makes much more sense if you think of Groovy as a platform to build DSLs. You may not want a user to have a complete language at hand. In the example below, we will demonstrate it using an example of language that only allows arithmetic operations, but this customizer allows you to:

allow/disallow creation of closures

allow/disallow imports

allow/disallow package definition

allow/disallow definition of methods

restrict the receivers of method calls

restrict the kind of AST expressions a user can use

restrict the tokens (grammar-wise) a user can use

restrict the types of the constants that can be used in code

For all those features, the secure AST customizer works using either an allowed list (list of elements that are permitted)  or a disallowed list (list of elements that are not permitted). For each type of feature (imports, tokens, …) you have the choice to use either an allowed or disallowed list, but you can mix dis/allowed lists for distinct features. Typically, you will choose allowed lists (which permits only the constructs listed and disallows all others).

use for token types from
you can use class literals here

If what the secure AST customizer provides out of the box isn’t enough for your needs, before creating your own compilation customizer, you might be interested in the expression and statement checkers that the AST customizer supports. Basically, it allows you to add custom checks on the AST tree, on expressions (expression checkers) or statements (statement checkers). For this, you must implement  org.codehaus.groovy.control.customizers.SecureASTCustomizer.StatementChecker or  org.codehaus.groovy.control.customizers.SecureASTCustomizer.ExpressionChecker .

Those interfaces define a single method called  isAuthorized , returning a boolean, and taking a  Statement (or  Expression ) as a parameter. It allows you to perform complex logic over expressions or statements to tell if a user is allowed to do it or not.

For example, there’s no predefined configuration flag in the customizer which will let you prevent people from using an attribute expression. Using a custom checker, it is trivial:

Then we can make sure that this works by evaluating a simple script:

will fail compilation

Statements can be checked using org.codehaus.groovy.control.customizers.SecureASTCustomizer.StatementChecker Expressions can be checked using org.codehaus.groovy.control.customizers.SecureASTCustomizer.ExpressionChecker

This customizer may be used as a filter on other customizers. The filter, in that case, is the  org.codehaus.groovy.control.SourceUnit . For this, the source aware customizer takes another customizer as a delegate, and it will apply customization of that delegate only and only if predicates on the source unit match.

SourceUnit gives you access to multiple things but in particular the file being compiled (if compiling from a file, of course). It gives you the potential to perform operation based on the file name, for example. Here is how you would create a source aware customizer:

Then you can use predicates on the source aware customizer:

Customizer builder

If you are using compilation customizers in Groovy code (like the examples above) then you can use an alternative syntax to customize compilation. A builder ( org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder ) simplifies the creation of customizers using a hierarchical DSL.

static import of the builder method
configuration goes here

The code sample above shows how to use the builder. A static method,  withConfig , takes a closure corresponding to the builder code, and automatically registers compilation customizers to the configuration. Every compilation customizer available in the distribution can be configured this way:

apply @Log transparently
apply @Log with a different name for the logger
apply CompileStatic AST annotation on .sgroovy files
apply CompileStatic AST annotation on .sgroovy or .sg files
apply CompileStatic AST annotation on files whose name is 'foo'
apply CompileStatic AST annotation on files whose name is 'foo' or 'bar'
apply CompileStatic AST annotation on files that do not contain a class named 'Baz'

Inlined customizer allows you to write a compilation customizer directly, without having to create a class for it.

define an inlined customizer which will execute at the CONVERSION phase
prints the name of the class node being compiled

Of course, the builder allows you to define multiple customizers at once:

The configscript commandline parameter

So far, we have described how you can customize compilation using a  CompilationConfiguration class, but this is only possible if you embed Groovy and that you create your own instances of  CompilerConfiguration (then use it to create a GroovyShell , GroovyScriptEngine , …).

If you want it to be applied on the classes you compile with the normal Groovy compiler (that is to say with groovyc , ant or gradle , for example), it is possible to use a commandline parameter named configscript that takes a Groovy configuration script as argument.

This script gives you access to the CompilerConfiguration instance  before the files are compiled (exposed into the configuration script as a variable named configuration ), so that you can tweak it.

It also transparently integrates the compiler configuration builder above. As an example, let’s see how you would activate static compilation by default on all classes.

Normally, classes in Groovy are compiled with a dynamic runtime. You can activate static compilation by placing an annotation named @CompileStatic on any class. Some people would like to have this mode activated by default, that is to say not having to annotate (potentially many) classes. Using configscript , makes this possible. First of all, you need to create a file named config.groovy into say src/conf with the following contents:

references a instance

That is actually all you need. You don’t have to import the builder, it’s automatically exposed in the script. Then, compile your files using the following command line:

We strongly recommend you to separate configuration files from classes, hence why we suggest using the src/main and src/conf directories above.

In a configuration script you can also set system properties, e.g.:

If you have numerous system properties to set, then using a configuration file will reduce the need to set a bunch of system properties with a long command line or appropriately defined environment variable. You can also share all the settings by simply sharing the config file.

runtime metaprogramming doesn’t allow you to do what you want

you need to improve the performance of the execution of your DSLs

you want to leverage the same syntax as Groovy but with different semantics

you want to improve support for type checking in your DSLs

Then AST transformations are the way to go. Unlike the techniques used so far, AST transformations are meant to change or generate code before it is compiled to bytecode. AST transformations are capable of adding new methods at compile time for example, or totally changing the body of a method based on your needs. They are a very powerful tool but also come at the price of not being easy to write. For more information about AST transformations, please take a look at the compile-time metaprogramming section of this manual.

It may be interesting, in some circumstances, to provide feedback about wrong code to the user as soon as possible, that is to say when the DSL script is compiled, rather than having to wait for the execution of the script. However, this is not often possible with dynamic code. Groovy actually provides a practical answer to this known as type checking extensions .

3.21.8. Builders

Many tasks require building things and the builder pattern is one technique used by developers to make building things easier, especially building of structures which are hierarchical in nature. This pattern is so ubiquitous that Groovy has special built-in support. Firstly, there are many built-in builders. Secondly, there are classes which make it easier to write your own builders.

Existing builders

Groovy comes with many built-in builders. Let’s look at some of them.

See Creating Xml - MarkupBuilder .

See Creating Xml - StreamingMarkupBuilder .

A builder for generating Simple API for XML (SAX) events.

If you have the following SAX handler:

You can use SaxBuilder to generate SAX events for the handler like this:

And then check that everything worked as expected:

A Groovy builder that works with Streaming API for XML (StAX) processors.

Here is a simple example using the StAX implementation of Java to generate XML:

An external library such as Jettison can be used as follows:

A builder for parsing HTML, XHTML and XML into a W3C DOM tree.

For example this XML String :

Can be parsed into a DOM tree with a DOMBuilder like this:

And then processed further e.g. by using DOMCategory :

NodeBuilder is used for creating nested trees of groovy.util.Node objects for handling arbitrary data. To create a simple user list you use a NodeBuilder like this:

Now you can process the data further, e.g. by using GPath expressions :

Groovy’s JsonBuilder makes it easy to create Json. For example to create this Json string:

you can use a JsonBuilder like this:

We use JsonUnit to check that the builder produced the expected result:

If you need to customize the generated output you can pass a JsonGenerator instance when creating a JsonBuilder :

Unlike JsonBuilder which creates a data structure in memory, which is handy in those situations where you want to alter the structure programmatically before output, StreamingJsonBuilder directly streams to a writer without any intermediate memory data structure. If you do not need to modify the structure and want a more memory-efficient approach, use StreamingJsonBuilder .

The usage of StreamingJsonBuilder is similar to JsonBuilder . In order to create this Json string:

you use a StreamingJsonBuilder like this:

We use JsonUnit to check the expected result:

If you need to customize the generated output you can pass a JsonGenerator instance when creating a StreamingJsonBuilder :

SwingBuilder allows you to create full-fledged Swing GUIs in a declarative and concise fashion. It accomplishes this by employing a common idiom in Groovy, builders. Builders handle the busywork of creating complex objects for you, such as instantiating children, calling Swing methods, and attaching these children to their parents. As a consequence, your code is much more readable and maintainable, while still allowing you to access to the full range of Swing components.

Here’s a simple example of using SwingBuilder :

Here is what it will look like:

SwingBuilder001

This hierarchy of components would normally be created through a series of repetitive instantiations, setters, and finally attaching this child to its respective parent. Using SwingBuilder , however, allows you to define this hierarchy in its native form, which makes the interface design understandable simply by reading the code.

The flexibility shown here is made possible by leveraging the many programming features built-in to Groovy, such as closures, implicit constructor calling, import aliasing, and string interpolation. Of course, these do not have to be fully understood in order to use SwingBuilder ; as you can see from the code above, their uses are intuitive.

Here is a slightly more involved example, with an example of SwingBuilder code re-use via a closure.

Here’s another variation that relies on observable beans and binding:

@Bindable is one of the core AST Transformations. It generates all the required boilerplate code to turn a simple bean into an observable one. The bind() node creates appropriate PropertyChangeListeners that will update the interested parties whenever a PropertyChangeEvent is fired.

Here we describe which lets you write Ant build scripts in Groovy rather than XML. You may also be interested in using Groovy from Ant using the .

Despite being primarily a build tool, Apache Ant is a very practical tool for manipulating files including zip files, copy, resource processing, and more. But if ever you’ve been working with a build.xml file or some Jelly script and found yourself a little restricted by all those pointy brackets, or found it a bit weird using XML as a scripting language and wanted something a little cleaner and more straight forward, then maybe Ant scripting with Groovy might be what you’re after.

Groovy has a helper class called AntBuilder which makes the scripting of Ant tasks really easy; allowing a real scripting language to be used for programming constructs (variables, methods, loops, logical branching, classes etc). It still looks like a neat concise version of Ant’s XML without all those pointy brackets; though you can mix and match this markup inside your script. Ant itself is a collection of jar files. By adding them to your classpath, you can easily use them within Groovy as is. We believe using AntBuilder leads to more concise and readily understood syntax.

AntBuilder exposes Ant tasks directly using the convenient builder notation that we are used to in Groovy. Here is the most basic example, which is printing a message on the standard output:

creates an instance of
executes the task with the message in parameter

Imagine that you need to create a ZIP file. It can be as simple as:

In the next example, we demonstrate the use of AntBuilder to copy a list of files using a classical Ant pattern directly in Groovy:

Another example would be iterating over a list of files matching a specific pattern:

Or executing a JUnit test:

We can even go further by compiling and executing a Java file directly from Groovy:

It is worth mentioning that AntBuilder is included in Gradle , so you can use it in Gradle just like you would in Groovy. Additional documentation can be found in the Gradle manual .

CliBuilder provides a compact way to specify the available options for a commandline application and then automatically parse the application’s commandline parameters according to that specification. By convention, a distinction is made between option commandline parameters and any remaining parameters which are passed to an application as its arguments. Typically, several types of options might be supported such as -V or --tabsize=4 . CliBuilder removes the burden of developing lots of code for commandline processing. Instead, it supports a somewhat declarative approach to declaring your options and then provides a single call to parse the commandline parameters with a simple mechanism to interrogate the options (you can think of this as a simple model for your options).

Even though the details of each commandline you create could be quite different, the same main steps are followed each time. First, a CliBuilder instance is created. Then, allowed commandline options are defined. This can be done using a dynamic api style or an annotation style. The commandline parameters are then parsed according to the options specification resulting in a collection of options which are then interrogated.

Here is a simple example Greeter.groovy script illustrating usage:

Earlier versions of Groovy had a CliBuilder in the package and no import was necessary. In Groovy 2.5, this approach became deprecated: applications should instead choose the or version. The groovy.util version in Groovy 2.5 points to the commons-cli version for backwards compatibility but has been removed in Groovy 3.0.
define a new instance specifying an optional usage string
specify a option taking a single argument with an optional long variant
specify a option taking no arguments with an optional long variant
parse the commandline parameters supplied to the script
if the option is found display a usage message
display a standard greeting or, if the option is found, a customized greeting

Running this script with no commandline parameters, i.e.:

results in the following output:

Running this script with -h as the single commandline parameter, i.e.:

Running this script with --audience Groovologist as the commandline parameters, i.e.:

When creating the CliBuilder instance in the above example, we set the optional usage property within the constructor call. This follows Groovy’s normal ability to set additional properties of the instance during construction. There are numerous other properties which can be set such as header and footer . For the complete set of available properties, see the available properties for the groovy.util.CliBuilder class.

When defining an allowed commandline option, both a short name (e.g. "h" for the help option shown previously) and a short description (e.g. "display usage" for the help option) must be supplied. In our example above, we also set some additional properties such as longOpt and args . The following additional properties are supported when specifying an allowed commandline option:

Name Description Type

argName

the name of the argument for this option used in output

longOpt

the long representation or long name of the option

args

the number of argument values

or     (1)

optionalArg

whether the argument value is optional

required

whether the option is mandatory

type

the type of this option

valueSeparator

the character that is the value separator

    (2)

defaultValue

a default value

convert

converts the incoming String to the required type

    (1)

(1) More details later (2) Single character Strings are coerced to chars in special cases in Groovy

If you have an option with only a longOpt variant, you can use the special shortname of '_' to specify the option, e.g. : cli._(longOpt: 'verbose', 'enable verbose logging') . Some of the remaining named parameters should be fairly self-explanatory while others deserve a bit more explanation. But before further explanations, let’s look at ways of using CliBuilder with annotations.

Rather than making a series of method calls (albeit in a very declarative mini-DSL form) to specify the allowable options, you can provide an interface specification of the allowable options where annotations are used to indicate and provide details for those options and for how unprocessed parameters are handled. Two annotations are used: groovy.cli.Option and groovy.cli.Unparsed .

Here is how such a specification can be defined:

Specify a Boolean option set using or
Specify a String option set using or
Specify where any remaining parameters will be stored

Note how the long name is automatically determined from the interface method name. You can use the longName annotation attribute to override that behavior and specify a custom long name if you wish or use a longName of '_' to indicate that no long name is to be provided. You will need to specify a shortName in such a case.

Here is how you could use the interface specification:

Create a instance as before with optional properties
Parse parameters using the interface specification
Interrogate options using the methods from the interface
Parse a different set of parameters
Interrogate the remaining parameters

When parseFromSpec is called, CliBuilder automatically creates an instance implementing the interface and populates it. You simply call the interface methods to interrogate the option values.

Alternatively, perhaps you already have a domain class containing the option information. You can simply annotate properties or setters from that class to enable CliBuilder to appropriately populate your domain object. Each annotation both describes that option’s properties through the annotation attributes and indicates the setter the CliBuilder will use to populate that option in your domain object.

Indicate that a Boolean property is an option
Indicate that a String property (with explicit setter) is an option
Specify where any remaining args will be stored

And here is how you could use the specification:

Create a instance as before with optional parameters
Create an instance for to populate
Parse arguments populating the supplied instance
Interrogate the String option property
Interrogate the remaining arguments property

When parseFromInstance is called, CliBuilder automatically populates your instance. You simply interrogate the instance properties (or whatever accessor methods you have provided in your domain object) to access the option values.

Finally, there are two additional convenience annotation aliases specifically for scripts. They simply combine the previously mentioned annotations and groovy.transform.Field . The groovydoc for those annotations reveals the details: groovy.cli.OptionField and groovy.cli.UnparsedField .

Here is an example using those annotations in a self-contained script that would be called with the same arguments as shown for the instance example earlier:

We saw in our initial example that some options act like flags, e.g. Greeter -h but others take an argument, e.g. Greeter --audience Groovologist . The simplest cases involve options which act like flags or have a single (potentially optional) argument. Here is an example involving those cases:

An option that is simply a flag - the default; setting args to 0 is allowed but not needed.
An option with exactly one argument
An option with an optional argument; it acts like a flag if the option is left out
An example using this spec where an argument is supplied to the 'c' option
An example using this spec where no argument is supplied to the 'c' option; it’s just a flag

Note: when an option with an optional argument is encountered, it will (somewhat) greedily consume the next parameter from the supplied commandline parameters. If however, the next parameter matches a known long or short option (with leading single or double hyphens), that will take precedence, e.g. -b in the above example.

Option arguments may also be specified using the annotation style. Here is an interface option specification illustrating such a definition:

And here is how it is used:

This example makes use of an array-typed option specification. We cover this in more detail shortly when we discuss multiple arguments.

Arguments on the commandline are by nature Strings (or arguably can be considered Booleans for flags) but can be converted to richer types automatically by supplying additional typing information. For the annotation-based argument definition style, these types are supplied using the field types for annotation properties or return types of annotated methods (or the setter argument type for setter methods). For the dynamic method style of argument definition a special 'type' property is supported which allows you to specify a Class name.

When an explicit type is defined, the args named-parameter is assumed to be 1 (except for Boolean-typed options where it is 0 by default). An explicit args parameter can still be provided if needed. Here is an example using types with the dynamic api argument definition style:

Primitives, numeric types, files, enums and arrays thereof, are supported (they are converted using org.codehaus.groovy.runtime.StringGroovyMethods#asType ).

If the supported types aren’t sufficient, you can supply a closure to handle the String to rich type conversion for you. Here is a sample using the dynamic api style:

Alternatively, you can use the annotation style by supplying the conversion closure as an annotation parameter. Here is an example specification:

And an example using that specification:

Multiple arguments are also supported using an args value greater than 1. There is a special named parameter, valueSeparator , which can also be optionally used when processing multiple arguments. It allows some additional flexibility in the syntax supported when supplying such argument lists on the commandline. For example, supplying a value separator of ',' allows a comma-delimited list of values to be passed on the commandline.

The args value is normally an integer. It can be optionally supplied as a String. There are two special String symbols: ` and `\*`. The `*` value means 0 or more. The ` value means 1 or more. The * value is the same as using + and also setting the optionalArg value to true.

Accessing the multiple arguments follows a special convention. Simply add an 's' to the normal property you would use to access the argument option and you will retrieve all the supplied arguments as a list. So, for a short option named 'a', you access the first 'a' argument using options.a and the list of all arguments using options.as . It’s fine to have a shortname or longname ending in 's' so long as you don’t also have the singular variant without the 's'. So, if name is one of your options with multiple arguments and guess is another with a single argument, there will be no confusion using options.names and options.guess .

Here is an excerpt highlighting the use of multiple arguments:

Args value supplied as a String and comma value separator specified
One or more arguments are allowed
Two commandline parameters will be supplied as the 'b' option’s list of arguments
Access the 'a' option’s first argument
Access the 'a' option’s list of arguments
An alternative syntax for specifying two arguments for the 'a' option
The arguments to the 'b' option supplied as a comma-separated value

As an alternative to accessing multiple arguments using the plural name approach, you can use an array-based type for the option. In this case, all options will always be returned via the array which is accessed via the normal singular name. We’ll see an example of this next when discussing types.

Multiple arguments are also supported using the annotation style of option definition by using an array type for the annotated class member (method or property) as this example shows:

And used as follows:

Here is an example using types and multiple arguments with the dynamic api argument definition style:

For an array type, the trailing 's' can be used but isn’t needed

Groovy makes it easy using the Elvis operator to provide a default value at the point of usage of some variable, e.g. String x = someVariable ?: 'some default' . But sometimes you wish to make such a default part of the options specification to minimise the interrogators work in later stages. CliBuilder supports the defaultValue property to cater for this scenario.

Here is how you could use it using the dynamic api style:

Similarly, you might want such a specification using the annotation style. Here is an example using an interface specification:

Which would be used like this:

You can also use the defaultValue annotation attribute when using annotations with an instance, though it’s probably just as easy to provide an initial value for the property (or backing field).

The dynamic api style of using CliBuilder is inherently dynamic but you have a few options should you want to make use of Groovy’s static type checking capabilities. Firstly, consider using the annotation style, for example, here is an interface option specification:

And it can be used in combination with @TypeChecked as shown here:

Secondly, there is a feature of the dynamic api style which offers some support. The definition statements are inherently dynamic but actually return a value which we have ignored in earlier examples. The returned value is in fact a TypedOption<Type> and special getAt support allows the options to be interrogated using the typed option, e.g. options[savedTypeOption] . So, if you have statements similar to these in a non type checked part of your code:

Then, the following statements can be in a separate part of your code which is type checked:

Finally, there is one additional convenience method offered by CliBuilder to even allow the definition part to be type checked. It is a slightly more verbose method call. Instead of using the short name (the opt name) in the method call, you use a fixed name of option and supply the opt value as a property. You must also specify the type directly as shown in the following example:

Advanced CLI features

can be thought of as a Groovy friendly wrapper on top of either or . If there is a feature not provided by that you know is supported in the underlying library, the current implementation (and various Groovy language features) make it easy for you to call the underlying library methods directly. Doing so is a pragmatic way to leverage the Groovy-friendly syntax offered by and yet still access some of the underlying library’s advanced features. A word of caution however; future versions of could potentially use another underlying library and in that event, some porting work may be required for your Groovy classes and/or scripts.

As an example, here is some code for making use of Apache Commons CLI’s grouping mechanism:

The parse will fail since only one option from a group can be used at a time.

Below are some features available in the picocli version of CliBuilder .

New property: errorWriter

When users of your application give invalid command line arguments, CliBuilder writes an error message and the usage help message to the stderr output stream. It doesn’t use the stdout stream to prevent the error message from being parsed when your program’s output is used as input for another process. You can customize the destination by setting the errorWriter to a different value.

On the other hand, CliBuilder.usage() prints the usage help message to the stdout stream. This way, when users request help (e.g. with a --help parameter), they can pipe the output to a utility like less or grep .

You can specify different writers for testing. Be aware that for backwards compatibility, setting the writer property to a different value will set both the writer and the errorWriter to the specified writer.

ANSI colors

The picocli version of CliBuilder renders the usage help message in ANSI colors on supported platforms automatically. If desired you can customize this. (An example follows below.)

New property: name

As before, you can set the synopsis of the usage help message with the usage property. You may be interested in a small improvement: if you only set the command name , a synopsis will be generated automatically, with repeating elements followed by …​ and optional elements surrounded with [ and ] . (An example follows below.)

New property: usageMessage

This property exposes a UsageMessageSpec object from the underlying picocli library, which gives fine-grained control over various sections of the usage help message. For example:

Gives this output:

usageMessageSpec

Property: parser

The parser property gives access to the picocli ParserSpec object that can be used to customize the parser behavior.

This can be useful when the CliBuilder options to control the parser are not fine-grained enough. For example, for backward compatibility with the Commons CLI implementation of CliBuilder , by default CliBuilder stops looking for options when an unknown option is encountered, and subsequent command line arguments are treated as positional parameters. CliBuilder provides a stopAtNonOption property, and by setting this to false you can make the parser more strict, so an unknown option results in error: Unknown option: '-x' .

But what if you want to treat unknown options as positional parameters, and still process subsequent command line arguments as options?

This can be accomplished with the parser property. For example:

See the documentation for details.

Map options

Finally, if your application has options that are key-value pairs, you may be interested in picocli’s support for maps. For example:

Previously, pairs were split up into parts and added to a list
Picocli map support: simply specify as the type of the option
You can even specify the type of the map elements
To compare, let’s specify two key-value pairs for each option
Previously, all key-value pairs end up in a list and it is up to the application to work with this list
Picocli returns the key-value pairs as a
Both keys and values of the map can be strongly typed

Controlling the Picocli version

To use a specific version of picocli, add a dependency to that version in your build configuration. If running scripts using a pre-installed version of Groovy, use the @Grab annotation to control the version of picocli to use in CliBuilder .

ObjectGraphBuilder is a builder for an arbitrary graph of beans that follow the JavaBean convention. It is in particular useful for creating test data.

Let’s start with a list of classes that belong to your domain:

Then using ObjectGraphBuilder building a Company with three employees is as easy as:

creates a new object graph builder
sets the classloader where the classes will be resolved
sets the base package name for classes to be resolved
creates a instance
with 3 instances
each of them having a distinct

Behind the scenes, the object graph builder:

will try to match a node name into a Class , using a default ClassNameResolver strategy that requires a package name

then will create an instance of the appropriate class using a default NewInstanceResolver strategy that calls a no-arg constructor

resolves the parent/child relationship for nested nodes, involving two other strategies:

RelationNameResolver will yield the name of the child property in the parent, and the name of the parent property in the child (if any, in this case, Employee has a parent property aptly named company )

ChildPropertySetter will insert the child into the parent taking into account if the child belongs to a Collection or not (in this case employees should be a list of Employee instances in Company ).

All 4 strategies have a default implementation that work as expected if the code follows the usual conventions for writing JavaBeans. In case any of your beans or objects do not follow the convention you may plug your own implementation of each strategy. For example imagine that you need to build a class which is immutable:

Then if you try to create a Person with the builder:

It will fail at runtime with:

Fixing this can be done by changing the new instance strategy:

ObjectGraphBuilder supports ids per node, meaning that you can store a reference to a node in the builder. This is useful when multiple objects reference the same instance. Because a property named id may be of business meaning in some domain models ObjectGraphBuilder has a strategy named IdentifierResolver that you may configure to change the default name value. The same may happen with the property used for referencing a previously saved instance, a strategy named ReferenceResolver will yield the appropriate value (default is `refId'):

an address can be created with an
an employee can reference the address directly with its id
or use the attribute corresponding to the of the corresponding address

Its worth mentioning that you cannot modify the properties of a referenced bean.

See Working with JMX - JmxBuilder for details.

groovy.util.FileTreeBuilder is a builder for generating a file directory structure from a specification. For example, to create the following tree:

You can use a FileTreeBuilder like this:

To check that everything worked as expected we use the following `assert`s:

FileTreeBuilder also supports a shorthand syntax:

This produces the same directory structure as above, as shown by these `assert`s:

Creating a builder

While Groovy has many built-in builders, the builder pattern is so common, you will no doubt eventually come across a building requirement that hasn’t been catered for by those built-in builders. The good news is that you can build your own. You can do everything from scratch by relying on Groovy’s metaprogramming capabilities. Alternatively, the BuilderSupport and FactoryBuilderSupport classes make designing your own builders much easier.

One approach to building a builder is to subclass BuilderSupport . With this approach, the general idea is to override one or more of a number of lifecycle methods including setParent , nodeCompleted and some or all of the createNode methods from the BuilderSupport abstract class.

As an example, suppose we want to create a builder of tracking athletic training programs. Each program is made up of a number of sets and each set has its own steps. A step might itself be a set of smaller steps. For each set or step , we might wish to record the distance required (or time ), whether to repeat the steps a certain number of times, whether to take a break between each step and so forth.

For the simplicity of this example, we’ll capture the training programming using maps and lists. A set has a list of steps. Information like repeat count or distance will be tracked in a map of attributes for each step and set.

The builder implementation is as follows:

Override a couple of the createNode methods. We’ll create a map capturing the set name, an empty list of steps, and potentially some attributes.

Whenever we complete a node we’ll add the node to the list of steps for the parent (if any).

The code looks like this:

Next, we’ll write a little helper method which recursively adds up the distances of all substeps, accounting for repeated steps as needed.

Finally, we can now use our builder and helper method to create a swimming training program and check its total distance:

A second approach to building a builder is to subclass FactoryBuilderSupport . This builder has similar goals to BuilderSupport but with extra features to simplify domain class construction.

With this approach, the general idea is to override one or more of a number of lifecycle methods including resolveFactory , nodeCompleted and postInstantiate methods from the FactoryBuilderSupport abstract class.

We’ll use the same example as for the previous BuilderSupport example; a builder of tracking athletic training programs.

For this example, rather than capturing the training programming using maps and lists, we’ll use some simple domain classes.

Override the resolveFactory method to return a special factory which returns classes by capitalizing the names used in our mini DSL.

The code, including the code for the special factory class, looks like this:

Rather than using lists and maps, we’ll have some simple domain classes and related traits:

Just like for the BuilderSupport example, it is useful to have a helper method to calculate the total distance covered during the training session. The implementation is very similar to our earlier example, but is adjusted to work well with our newly defined traits.

Finally, we can now use our new builder and helper methods to create a cycling training program and check its total distance:

3.22. Working with JMX

The Java Management Extensions (JMX) technology provides a standard way of managing resources such as applications, devices, and services on the JDK. Each resource to be managed is represented by a Managed Bean (or MBean ). Given that Groovy sits directly on top of Java, Groovy can leverage the tremendous amount of work already done for JMX with Java. In addition, Groovy provides a GroovyMBean class, in the groovy-jmx module, which makes an MBean look like a normal Groovy object and simplifies Groovy code for interacting with MBeans. For example, the following code:

can be simplified to:

The remainder of this page shows you how to:

Monitor the JVM using MXBeans

Monitor Apache Tomcat and display statistics

Monitor Oracle OC4J and display information

Monitor BEA WebLogic and display information

Leverage Spring’s MBean annotation support to export your Groovy beans as MBeans

MBeans are not accessed directly by an application but are managed by a repository called an MBean server . Java includes a special MBean server called the platform MBean server , which is built into the JVM. Platform MBeans are registered in this server using unique names.

You can monitor the JVM through its platform MBeans with the following code:

When run, you will see something like this:

First start up Tomcat with JMX monitoring enabled by setting the following:

You can do this in your startup script and may choose any available port, we used 9004.

The following code uses JMX to discover the available MBeans in the running Tomcat, determine which are web modules, extract the processing time for each web module and displays the result in a graph using JFreeChart:

When run, we will see a trace of progress being made:

The output will look like this:

catalina

Note: if you get errors running this script, see the Troubleshooting section below.

Here is a script to access OC4J and print out some information about the server, its runtime and (as an example) the configured JMS destinations:

Here is the result of running this script:

As a slight variation, this script displays a pie chart of memory usage using JFreeChart:

Which looks like:

oc4jpie

This script prints out information about the server followed by information about JMS Destinations (as an example). Many other mbeans are available .

Here is the output:

You can also use Spring to automatically register beans as JMX aware.

Here is an example class (Calculator.groovy):

Here is the Spring configuration file (beans.xml):

Here is a script which uses this bean and configuration:

And here is the resulting output:

You can even attach to the process while it is running with jconsole . It will look something like:

jconsole

We started the Groovy application with the -Dcom.sun.management.jmxremote JVM argument.

Dynamic language beans in Spring

Spring JMX Documentation

3.22.7. Troubleshooting

If you get the following error, your container’s JMX access is password protected:

To fix that, add an environment with the credentials when connecting, like this (password has to be set before that):

Details for the software you are trying to monitor/manage may differ slightly. Check out the other examples using credentials above if appropriate (e.g. OC4J and WebLogic). If you still have troubles, you will have to consult the documentation for the software you are trying to monitor/manage for details on how to provide credentials.

3.22.8. JmxBuilder

JmxBuilder is a Groovy-based domain specific language for the Java Management Extension (JMX) API . It uses the builder pattern (FactoryBuilder) to create an internal DSL that facilitates the exposure of POJO’s and Groovy beans as management components via the MBean server. JmxBuilder hides the complexity of creating and exporting management beans via the JMX API and provides a set of natural Groovy constructs to interact with the JMX infrastructure.

To start using JmxBuilder, simply make sure the jar file is on your class path. Then you can do the following in your code:

That’s it! You are now ready to use the JmxBuilder.

You can pass in an instance of your own MBeanServer to the builder ( JmxBuilder(MBeanServer) )

If no MBeanServer is specified, the builder instance will default to the underlying platform MBeanServer.

Once you have an instance of JmxBuilder, you are now ready to invoke any of its builder nodes.

JMX Connectors

Remote connectivity is a crucial part of the JMX architecture. JmxBuilder facilitates the creation of connector servers and connector clients with a minimal amount of coding.

JmxBuilder.connectorServer() supports the full Connector api syntax and will let you specify properties, override the URL, specify your own host, etc.

Note that the serverConnector node will accept four ServerConnector property aliases (authenticate, passwordFile,accessFile, and sslEnabled). You can use these aliases or provided any of the RMI-supported properties.

Example - Connector Server (see correction below)

The snippet above returns an RMI connector that will start listening on port 9000. By default, the builder will internally generate URL "service:jmx:rmi:///jndi/rmi://localhost:9000/jmxrmi" .

NOTE: Sadly you are as likely to get something like the following when attempting to run the previous snippet of code (example is incomplete, see below):

This occurs on Mac and Linux (CentOS 5) with Groovy 1.6 installed. Perhaps there were assumptions made about the configuration of the /etc/hosts file?

Connector Example (Corrected) - Connector Server

The example above does not create the RMI registry. So, in order to export, you have to first export the RMI object registry (make sure to import java.rmi.registry.LocateRegistry ).

JmxBuilder.connectorClient() node lets you create JMX connector client object to connect to a JMX MBean Server.

Example - Client Connector

Creating a connector client can be done just as easily. With one line of code, you can create an instance of a JMX Connector Client as shown below.

You can then access the MBeanServerConnection associated with the connector using:

JmxBuilder MBean Export

You can export a Java object or a Groovy object with minimal coding. JmxBuilder will even find and export dynamic Groovy methods injected at runtime.

When using the builder, you can let JmxBuilder implicitly generate all of your MBean descriptor info. This is useful when you want to write minimal code to quickly export your beans. You can also explicitly declare all descriptor info for the bean. This gives you total control on how you want to describe every piece of information that you want to export for the underlying bean.

The JmxBuilder.export() node provides a container where all management entities to be exported to the MBeanServer are placed. You can place one or more bean() or timer() nodes as children of the export() node. JmxBuilder will automatically batch export the entities described by the nodes to the MBean server for management (see example below).

In the code snippet above, JmxBuilder.export() will export three management beans to the MBean server.

JmxBuilder.export() node supports the registrationPolicy parameter to specify how JmxBuilder will behave to resolve bean name collision during MBean registration:

replace - JmxBuilder.export() will replace any bean already registered with the MBean during export.

ignore - The bean being exported will be ignored if the same bean is already registered.

error - JmxBuilder.export() throws an error upon bean name collision during registration.

When you export an MBean to the MBeanServer, JmxBuilder will return an instance of GroovyMBean representing the management bean that have been exported by the builder. Nodes such as bean() and timer() will return an instances of GroovyMBean when they are invoked. The export() node returns an array of all of GroovyMBean[] representing all managed objects exported to the MBean server.

MBean Registration with JmxBuilder.bean()

This portion of this reference uses class RequestController to illustrate how to use JmxBuilder to export runtime management beans. The class is for illustration purpose and can be a POJO or a Groovy bean.

RequestController

As mentioned earlier, you can use JmxBuilder’s flexible syntax to export any POJO/POGO with no descriptor. The builder can automatically describe all aspects of the management beans using implicit defaults. These default values can easily be overridden as we’ll see in this in the next section.

The simplest way to export a POJO or POGO is listed below.

What this does:

First, the JmxBuilder.export() node will export an MBean to the MBeanServer representing the declared POJO instance.

The builder will generate a default ObjectName for the MBean and all other MBean descriptor information.

JmxBuilder will automatically export all declared attributes (MBean getter/setters), constructors , and operations on the instance.

The exported attributes will have read-only visibility.

Remember, JmxBuilder.export() returns an array of GroovyMBean[] objects for all exported instances. So, once you call JmxBuilder.export(), you have immediate access to the underlying MBean proxy (via GroovyMBean).

jconsole implicit export

The JmxBuilder.bean() node supports an extensive set of descriptors to describe your bean for management. The JMX MBeanServer uses these descriptors to expose metadata about the bean exposed for management.

Instead of describing the entire node, the following section explore each attribute separately.

Using the bean() node descriptors, you can specify your own MBean ObjectName.

The ObjectName can be specified as a String or an instance of the ObjectName.

Bean() Node - Attribute Export

JMX attributes are the setters and getters on the underlying bean. The JmxBuilder.bean() node provides several ways to flexibly describe and export MBean attributes. You can combine them however you want to achieve any level of attribute visibility. Let’s take a look.

The following code snippet will describe and export all attributes on the bean as read-only. JmxBuilder will use default values to describe the attributes that exported for management.

JmxBuilder will let you specify a list of attributes to export.

In the snippet above, only the "Resource" and "RequestCount" attributes will be exported . Again, since no descriptors are provided, JmxBuilder will use sensible defaults to describe the exported attributes.

One of the strengths of JmxBuilder is its flexibility in describing MBean. With the builder you can describe all aspects of the MBeans attribute that you want to export to the MBeanServer (see syntax above).

In the snippet above, attribute "Resource" is fully-described using all supported descriptors (i.e. desc, readable, writable, defaultValue) for a JMX attribute. However, we use the wildcard to describe attribute RequestCount and it will be exported and described using defaults.

Bean() Node - Constructor Export

JmxBuilder supports the explicit description and export of constructors defined in the underlying bean. There are several options available when exporting constructors. You can combine them however you want to achieve the desired level of manageability.

You can use the builder’s special "*" notation to export all constructors declared on the underlying bean. The builder will use default values to describe the MBean constructors.

JmxBuilder lets you target specific constructor to export by describing the parameter signature . This is useful when you have several constructors with different parameter signature and you want to export specific constructors.

Here, JmxBuilder will export a constructor that takes one parameter of type "Object" . Again, JmxBuilder will use default values to fill in the description of the constructor and the parameters.

JmxBuilder allows you to fully-describe the constructor that you want to target for export (see syntax above).

In the code above, JmxBuilder will target a constructor that takes one parameter for export to the MBeanServer. Notice how the constructor can be fully-described using all optional descriptor keys including parameter descriptors.

Bean() Node - Operation Export

Similar to constructors, JmxBuilder supports the description and export of MBean operations using a flexible notation (see above for syntax). You can combine these notations however you want to achieve the level of operation manageability desired.

You can use the builder’s special "*" notation to export all operations defined on the bean to be exposed for management. The builder will use default descriptor values for the operations being exported.

In this snippet, JmxBuilder will export all bean operations and will use default values to describe them in the MBeanServer.

JmxBuilder has a shorthand notation that lets you quickly target operations to be exported by providing a list of methods to export.

In the snippet above, the builder will only export methods start() and stop() . All other methods will be ignored. JmxBuilder will use default descriptor values to describe the operations being exported.

Using JmxBuilder, you can target methods to export for management using the methods' parameter signature. This is useful when you want to distinguish methods with the same name that you want to export (i.e. stop() instead of stop(boolean)).

In the snippet above, JmxBuilder would select method makeRequest(String) to be exported instead of the other version makeRequest() which takes no parameter. In this shorthand context, the signature is specified as a list of type (i.e. "String").

JmxBuilder supports detailed descriptors for bean operations. You can supply deep descriptor info about any operation on your bean including a name, description, method parameters, parameter type, and parameter description.

The snippet above shows all the ways JmxBuilder allows you to describe an operation targeted for management:

Operations start() and stop() are described by the "desc" key (this is enough since there are no params).

In operation setResource() uses of a shorthand version of params : to describe the parameters for the method.

makeRequest() uses the extended descriptor syntax to describe all aspects of the operation.

JmxBuilder supports the ability to embed descriptors directly in your Groovy class . So, instead of wrapping your description around the declared object (as we’ve seen here), you can embed your JMX descriptors directly in your class.

RequestControllerGroovy

There are two things going on in the code above:

Groovy class RequestControllerGroovy is defined and includes a static descriptor member. That member is used to declare a JmxBuilder descriptor to describe member of the class targeted for JMX export.

The second part of the code shows how to use JmxBuilder to export that class for management.

Timer Export

JMX standards mandate that the implementation of the API makes available a timer service. Since JMX is a component-based architecture, timers provide an excellent signalling mechanism to communicate to registered listener components in the MBeanServer. JmxBuilder supports the creation and export of timers using the same easy syntax we’ve seen so far.

The timer() node supports several attributes:

name : - Required The qualified JMX ObjectName instance (or String) for the timer.

event : - The JMX event type string that will be broadcast with every timing signal (default "jmx.builder.event" ).

message : - An optional string value that can be sent to listeners.

data : - An optional object that can be sent to listeners of timing signal.

startDate : - When to start timer. Set of valid values [ "now", date object ]. Default is "now"

period : - A timer’s period expressed as either a number of millisecond or time unit (day, hour, minute, second). See description below.

occurrences : - A number indicating the number of time to repeat timer. Default is forever.

This snippet above describes, creates, and exports a standard JMX Timer component. Here, the timer() node returns a GroovyMBean that represents the registered timer MBean in the MBeanServer.

An alternative way of exporting timers is within the JmxBuilder.export() node.

The timer() node supports a flexible notation for specifying the timer period values . You can specify the time in second, minutes, hour, and day. The default is millisecond.

timer( period: 100 ) = 100 millisecond

timer( period: "1s" ) = 1 second

timer( period: "1m" ) = 1 minute

timer( period: "1h" ) = 1 hour

timer( period: "1d" ) = 1 day

The node will automatically translate.

JmxBuilder and Events

An integral part of JMX is its event model . Registered management beans can communicate with each other by broadcasting events on the MBeanServer’s event bus. JmxBuilder provides several ways to easily listen and react to events broadcasted on the MBeanServer’s event bus. Developers can capture any event on the bus or throw their own to be consumed by other components registered on the MBeanServer.

Event Handling Closures

JmxBuilder leverages Groovy’s use of closures to provide simple, yet elegant, mean of reacting to JMX events. JmxBuilder supports two closure signatures:

JmxBuilder executes the closure and passes no information about the event that was captured on the bus.

JmxBuilder will pass an "event" object to the closure using this format. The event object contains information about the event was intercepted so that it can be handled by the handler. The parameter will contain different set of info depending on the event that was captured.

When describing attributes (see bean() node section above), you can provide a closure (or method pointer) for callback to be executed when the value of the attribute is updated on the exported MBean. This gives developers an opportunity to listen to and react to state changes on the MBean.

The sample snippet above shows how to specify an "onChange" callback closure when describing MBean attributes. In this sample code, whenever attribute "Resource" is updated via the exported MBean, the onChange event will be executed .

When handling the attribute onChange event, the handler closure will receive an event object with the following info:

event. oldValue - the previous attribute value before the change event.

event. newValue - the new value of the attribute after the change.

event. attribute - the name of the attribute on which the event occurred.

event. attributeType - the data type of the attribute that causes the event.

event. sequenceNumber - a numeric value representing the sequence number of event.

event. timeStamp - a time stamp for the event occurrence.

Similar to mbean attributes, JmxBuilder affords developers the ability to listen for operation invocation on an MBean registered in the MBeaServer. JmxBuilder accepts a callback closure that will be executed after the MBean method has invoked .

The snippet above shows how to declare an "onCall" closure to be used as listener when operation "start()" is invoked on the MBean. This sample uses the method pointer syntax to illustrate the versatility of JmxBuilder.

When handling the operation onCall event, the callback closure will receive an event object with the following info:

event. event - the event type string that was broadcasted.

event. source - The object on which the method was invoked.

event. data - the data type of the attribute that causes the event.

Listener MBean

When you export an MBean with the bean() node, you can define events the MBean can listen and react to. The bean() node provides a "listeners:" attribute that lets you define event listeners that your bean can react to.

In the sample above, we see the syntax for adding listeners to an exported MBean .

First, a timer is exported and started.

Then, an MBean is declared that will listen to the timer event and do something meaningful.

The "heartbeat:" name is arbitrary and has no correlation to the timer declared above.

The source of the event is specified using the "from:" attribute .

You can also specify an event type you are interested in receiving from a broadcaster (since a broadcaster can be emitting multiple events).

In some cases, you will want to create stand-alone event listeners (not attached to exported MBeans). JmxBuilder provides the Listener() node to let you create JMX listeners that can listen to MBeanServer events. This is useful when creating JMX client applications to monitor/manage JMX agents on remote JMX MBeanServers.

Here is the description of the listener() node attributes:

event: An optional string that identifies the JMX event type to listen for.

from (required): The JMX ObjectName of the component to listen to. This can be specified as a string or an instance of ObjectName.

call: The closure to execute when the event is captured. This can also be specified as a Groovy method pointer.

Here is an example of JmxBuilder’s listener node:

This example shows how you can use a stand-alone listener (outside an MBean export). Here, we export a timer with a 1 second resolution. Then, we specify a listener to that timer that will print "beep" every second.

Emitting JMX Events

JmxBuilder provides the tools needed to broadcast your own events on the MBeanServer’s event bus. There are no restrictions on the event type you can broadcast. You simply declare your emitter and the event type that you want to send, then broadcast your event at any time. Any registered component in the MBeanServer can register themselves to listen to your events.

The attributes for the node Emitter() can be summarized as follows:

name: an optional JMX ObjectName used to register your emitter in the MBeanServer. Default is jmx.builder:type=Emitter,name=Emitter@OBJECT_HASH_VALUE

event: an option string value that describes the JMX event type. Default is "jmx.builder.event.emitter" .

The snippet declares the emitter using implicit descriptor syntax . JmxBuilder will do the followings:

Create and register an emitter MBean with a default ObjectName.

Setup a default event type with value "jmx.builder.event.emitter" .

Return a GroovyMBean representing the emitter.

As with other nodes in the builder, you can override all keys in the emitter() node . You can specify the ObjectName and the event type .

Once you have declared your emitter, you can broadcast your event.

The sample above shows the emitter sending an event , once it has been declared. Any JMX component registered in the MBeanServer can register to receive message from this emitter.

You can optionally pass data to the receiver when you send the message.

If you use an event listener closure (see above) that accepts a parameter , you can access that value.

Monitoring the Java Virtual Machine

Using Groovy for System Management

Groovier jconsole!

JMX Scripts with Eclipse Monkey

Using JMX to monitor Apache ActiveMQ

Creating Swing UIs is made easy thanks to the use of SwingBuilder .

Security is a complex and multi-faceted issue and needs to be addressed in a holistic way. Groovy offers some features to improve security, but organisations concerned about security should already be addressing other necessary aspects such as network security, file-system security, operating system security, database security, passwords and potentially encryption.

Also, since Groovy runs on the JDK and optionally uses other library dependencies, users should ensure their JDK and all dependencies are up-to-date with respect to the latest security fixes.

With regard to security issues that may affect the Groovy project itself, the project follows the Apache general guidelines for handling security vulnerabilities . See also the project’s security policy and list of past vulnerabilities .

By virtue of running on the JVM and following various Java conventions, Groovy programs offer some of the same security features as Java programs, including:

programs cannot access arbitrary memory locations

final variables cannot be changed

array bounds are checked

class loaders perform bytecode verification when loading classes

casting cannot be done to an incompatible class

access is available to APIs for encryption and authentication

Special security support is provided through:

groovy.lang.GroovyShell , groovy.lang.GroovyClassLoader and other parts of the Groovy runtime fully support the Java security manager which allows you to sandbox script execution with a security policy. (Note: this functionality might be scaled back in future Groovy versions or when running on particular JDK versions in line with JEP 411 )

org.codehaus.groovy.control.customizers.SecureASTCustomizer secures source code by controlling what code constructs are permitted or prohibited in a code base (or part of a code base)

Default XML processing has secure processing enabled and doctype definitions disabled

Groovy’s SQL processing features provide support to guard against SQL injection

Temporary directory creation protects against known security vulnerabilities such as privilege escalation if scripts are stored in operating system temp directories

3.25. Design patterns in Groovy

Using design patterns with Java is a well-established topic. Design patterns also apply to Groovy:

some patterns carry over directly (and can make use of normal Groovy syntax improvements for greater readability)

some patterns are no longer required because they are built right into the language or because Groovy supports a better way of achieving the intent of the pattern

some patterns that have to be expressed at the design level in other languages can be implemented directly in Groovy (due to the way Groovy can blur the distinction between design and implementation)

3.25.1. Patterns

Abstract factory pattern.

The Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. It embodies the intent of a normal factory, i.e. remove the need for code using an interface to know the concrete implementation behind the interface, but applies to a set of interfaces and selects an entire family of concrete classes which implement those interfaces.

As an example, I might have interfaces Button, TextField and Scrollbar. I might have WindowsButton, MacButton, FlashButton as concrete classes for Button. I might have WindowsScrollBar, MacScrollBar and FlashScrollBar as concrete implementations for ScrollBar. Using the Abstract Factory Pattern should allow me to select which windowing system (i.e. Windows, Mac, Flash) I want to use once and from then on should be able to write code that references the interfaces but is always using the appropriate concrete classes (all from the one windowing system) under the covers.

Suppose we want to write a game system. We might note that many games have very similar features and control.

We decide to try to split the common and game-specific code into separate classes.

First let’s look at the game-specific code for a Two-up game:

Now, let’s look at the game-specific code for a number guessing game:

Now, let’s write our factory code:

The important aspect of this factory is that it allows selection of an entire family of concrete classes.

Here is how we would use the factory:

Note that the first line configures which family of concrete game classes we will use. It’s not important that we selected which family to use by using the factory property as shown in the first line. Other ways would be equally valid examples of this pattern. For example, we may have asked the user which game they wanted to play or determined which game from an environment setting.

With the code as shown, the game might look like this when run:

If we change the first line of the script to GameFactory.factory = guessFactory, then the sample run might look like this:

Adapter Pattern

The Adapter Pattern (sometimes called the wrapper pattern) allows objects satisfying one interface to be used where another type of interface is expected. There are two typical flavours of the pattern: the delegation flavour and the inheritance flavour.

Suppose we have the following classes:

We can ask the RoundHole class if a RoundPeg fits in it, but if we ask the same question for a SquarePeg , then it will fail because the SquarePeg class doesn’t have a radius property (i.e. doesn’t satisfy the required interface).

To get around this problem, we can create an adapter to make it appear to have the correct interface. It would look like this:

We can use the adapter like this:

Which results in the following output:

Let’s consider the same example again using inheritance. First, here are the original classes (unchanged):

An adapter using inheritance:

Using the adapter:

The output:

As a variation of the previous examples, we could instead define the following interface:

We can then define an adapter as a closure as follows:

And use it like this:

As of Groovy 1.1, there is a built-in MetaClass which can automatically add properties and methods dynamically.

Here is how the example would work using that feature:

After you create a peg object, you can simply add a property to it on the fly. No need to change the original class and no need for an adapter class.

Bouncer Pattern

The Bouncer Pattern describes usage of a method whose sole purpose is to either throw an exception (when particular conditions hold) or do nothing. Such methods are often used to defensively guard pre-conditions of a method.

When writing utility methods, you should always guard against faulty input arguments. When writing internal methods, you may be able to ensure that certain pre-conditions always hold by having sufficient unit tests in place. Under such circumstances, you may reduce the desirability to have guards on your methods.

Groovy differs from other languages in that you frequently use the assert method within your methods rather than having a large number of utility checker methods or classes.

We might have a utility method such as:

And we would use it like this:

But a more Groovy way to do this would simply be like this:

As an alternative example, we might have this utility method:

But with Groovy we could just as easily use:

Chain of Responsibility Pattern

In the Chain of Responsibility Pattern, objects using and implementing an interface (one or more methods) are intentionally loosely coupled. A set of objects that implement the interface are organised in a list (or in rare cases a tree). Objects using the interface make requests from the first implementor object. It will decide whether to perform any action itself and whether to pass the request further down the line in the list (or tree). Sometimes a default implementation for some request is also coded into the pattern if none of the implementors respond to the request.

In this example, the script sends requests to the lister object. The lister points to a UnixLister object. If it can’t handle the request, it sends the request to the WindowsLister . If it can’t handle the request, it sends the request to the DefaultLister .

The output will be a list of files (with slightly different format depending on the operating system).

Here is a UML representation:

ChainOfResponsibilityClasses

For simple cases, consider simplifying your code by not requiring the chain of classes. Instead, use Groovy truth and the elvis operator as shown here:

Or Groovy’s switch as shown here:

Alternatively, for Groovy 3+, consider using streams of lambdas as shown here:

If your use of chain of responsibility involves frequent use of the instanceof operator, like here:

instanceof code smell

It could indicate that instead of using the chain of responsibility pattern, you might consider using richer types, perhaps in combination with Groovy’s multimethods. For example, perhaps this:

or using more traditional object-oriented style like this:

Other variations to this pattern:

we could have an explicit interface in the traditional example, e.g. Lister , to statically type the implementations but because of duck-typing this is optional

we could use a chain tree instead of a list, e.g. if (animal.hasBackbone()) delegate to VertebrateHandler else delegate to InvertebrateHandler

we could always pass down the chain even if we processed a request (no early return)

we could decide at some point to not respond and not pass down the chain (pre-emptive abort)

we could use Groovy’s meta-programming capabilities to pass unknown methods down the chain, e.g. combine chain of responsibility with the use of methodMissing

Command Pattern

The Command Pattern is a pattern for loosely coupling a client object which wants to execute a series of commands and receiver objects which enact those commands. Instead of talking to receivers directly, clients interact with an intermediary object which then relays the necessary commands to the receivers. The pattern is in common use within the JDK, for example the api:javax.swing.Action[] class in Swing decouples swing code from receivers like buttons, menu items and panels.

The class diagram showing the typical classes is:

CommandClasses

The sequence of interactions is as shown below for an arbitrary receiver:

CommandSequence

The relevant classes required for turning a light on and off (see the example in the earlier wikipedia reference) would be as follows:

Our client scripts sends execute commands to an intermediary and knows nothing about any specific receivers, or any specific action method names and arguments.

Given that Groovy has first-class function support, we can do away with the actual command classes (like SwitchOnCommand ) by instead using closures as shown here:

Command closures (here method closures) but could be lambdas/method references for Groovy 3+

We can simplify further using the JDK’s existing Runnable interface and using a switch map rather than a separate Switch class as shown here:

We have added an additional Door receiver to illustrate how to expand the original example. Running this script results in:

As a variation, if the command names aren’t important to us, we can forgo using the switch map and just have a list of tasks to invoke as shown here:

Composite Pattern

The Composite Pattern allows you to treat single instances of an object the same way as a group of objects. The pattern is often used with hierarchies of objects. Typically, one or more methods should be callable in the same way for either leaf or composite nodes within the hierarchy. In such a case, composite nodes typically invoke the same named method for each of their children nodes.

Consider this usage of the composite pattern where we want to call toString() on either Leaf or Composite objects.

CompositeClasses

In Java, the Component class is essential as it provides the type used for both leaf and composite nodes. In Groovy, because of duck-typing, we don’t need it for that purpose, however, it can still serve as a useful place to place common behaviour between the leaf and composite nodes.

For our purposes, we will assemble the following hierarchy of components.

Here is the code:

Here is the resulting output:

Decorator Pattern

The Decorator Pattern provides a mechanism to embellish the behaviour of an object without changing its essential interface. A decorated object should be able to be substituted wherever the original (non-decorated) object was expected. Decoration typically does not involve modifying the source code of the original object and decorators should be able to be combined in flexible ways to produce objects with several embellishments.

Suppose we have the following Logger class.

There might be times when it is useful to timestamp a log message, or times when we might want to change the case of the message. We could try to build all of this functionality into our Logger class. If we did that, the Logger class would start to be very complex. Also, everyone would obtain all of the features even when they might want only a small subset of the features. Finally, feature interaction would become quite difficult to control.

To overcome these drawbacks, we instead define two decorator classes. Uses of the Logger class are free to embellish their base logger with zero or more decorator classes in whatever order they desire. The classes look like this:

We can use the decorators like so:

You can see that we embellish the logger behaviour with both decorators. Because of the order we chose to apply the decorators, our log message comes out capitalised and the timestamp is in normal case. If we swap the order around, let’s see what happens:

Now the timestamp itself has also been changed to be uppercase.

Closures make it easy to represent code. We can use that fact to make a general purpose logger class that accepts the decoration code as a closure. This saves us defining many decoration classes.

We can use the same approach with lambdas:

Our previous decorators were specific to Logger objects. We can use Groovy’s Meta-Object Programming capabilities to create a decorator which is far more general purpose in nature. Consider this class:

It takes any class and decorates it so that any String method parameter will automatically be changed to lower case.

Just be careful with ordering here. The original decorators were restricted to decorating Logger objects. This decorator works with any object type, so we can’t swap the ordering around, i.e. this won’t work:

We could overcome this limitation be generating an appropriate Proxy type at runtime but we won’t complicate the example here.

You can also consider using the ExpandoMetaClass from Groovy 1.1 to dynamically embellish a class with behaviour. This isn’t the normal style of usage of the decorator pattern (it certainly isn’t nearly as flexible) but may help you to achieve similar results in some cases without creating a new class.

Here’s what the code looks like:

This achieves a similar result to applying a single decorator but we have no way to easily apply and remove embellishments on the fly.

Suppose we have a calculator class (Actually any class would do).

We might be interested in observing usage of the class over time. If it is buried deep within our codebase, it might be hard to determine when it is being called and with what parameters. Also, it might be hard to know if it is performing well. We can easily make a generic tracing decorator that prints out tracing information whenever any method on the Calc class is called and also provide timing information about how long it took to execute. Here is the code for the tracing decorator:

Here is how to use the class in a script:

And here is what you would see after running this script:

The above timing example hooks into the lifecycle of Groovy objects (via invokeMethod ). This is such an important style performing meta-programming that Groovy has special support for this style of decorating using interceptors .

Groovy even comes with a built-in TracingInterceptor . We can extend the built-in class like this:

Here is an example of using this new class:

And here is the output:

If you are trying to decorate an object (i.e. just a particular instance of the class, not the class generally), then you can use Java’s java.lang.reflect.Proxy . Groovy makes working with this easier than just Java. Below is a code sample taken out of a grails project that wraps a java.sql.Connection so that it’s close method is a no-op:

If there were many methods to intercept, then this approach could be modified to look up closure in a map by method name and invoke it.

The Spring Framework allows decorators to be applied with interceptors (you may have heard the terms advice or aspect ). You can leverage this mechanism from Groovy as well.

First define a class that you want to decorate (we’ll also use an interface as is normal Spring practice):

Here’s the interface:

Here’s the class:

Now, we define our wiring in a file called beans.xml as follows:

Now, our script looks like this:

And when we run it, we see the results:

You may have to adjust your logging.properties file for messages at log level FINEST to be displayed.

The following example is inspired by some of the early example code for the Panini programming language. These days, you’ll see this style used with async functions in JavaScript.

Delegation Pattern

The Delegation Pattern is a technique where an object’s behavior (public methods) is implemented by delegating responsibility to one or more associated objects.

Groovy allows the traditional style of applying the delegation pattern, e.g. see Replace Inheritance with Delegation .

The groovy.lang.ExpandoMetaClass allows usage of this pattern to be encapsulated in a library. This allows Groovy to emulate similar libraries available for the Ruby language.

Consider the following library class:

With this in your classpath, you can now apply the delegation pattern dynamically as shown in the following examples. First, consider we have the following classes:

We can now use the delegator to automatically borrow methods from the lender object to extend the Person class. We can borrow the methods as is or with a rename:

The first line above, adds the borrowFor method to the Person class by delegating to the lender object. The second line adds a getMoney method to the Person class by delegating to the lender object’s borrowAmount method.

Alternatively, we could borrow multiple methods like this:

Which adds these two methods to the Person class.

Or if we want all the methods, like this:

Which will make all the methods in the delegate object available in the Person class.

Alternatively, we can use a map notation to rename multiple methods:

Since version 1.6 you can use the built-in delegation mechanism which is based on AST transformation.

This make delegation even easier:

Flyweight Pattern

The Flyweight Pattern is a pattern for greatly reducing memory requirements by not requiring that heavy-weight objects be created in large numbers when dealing with systems that contain many things that are mostly the same. If for instance, a document was modelled using a complex character class that knew about unicode, fonts, positioning, etc., then the memory requirements could be quite large for large documents if each physical character in the document required its own character class instance. Instead, characters themselves might be kept within Strings and we might have one character class (or a small number such as one character class for each font type) that knew the specifics of how to deal with characters.

In such circumstances, we call the state that is shared with many other things (e.g. the character type) intrinsic state. It is captured within the heavy-weight class. The state which distinguishes the physical character (maybe just its ASCII code or Unicode) is called its extrinsic state.

First we are going to model some complex aircraft (the first being a hoax competitor of the second - though that is not relevant to the example).

b797 hoax

If we want to model our fleet, our first attempt might involve using many instances of these heavy-weight objects. It turns out though that only a few small pieces of state (our extrinsic state) change for each aircraft, so we will have singletons for the heavy-weight objects and capture the extrinsic state (bought date and asset number in the code below) separately.

So here, even if our fleet contained hundreds of planes, we would only have one heavy-weight object for each type of aircraft.

As a further efficiency measure, we might use lazy creation of the flyweight objects rather than create the initial map up front as in the above example.

Running this script results in:

The Iterator Pattern allows sequential access to the elements of an aggregate object without exposing its underlying representation.

Groovy has the iterator pattern built right in to many of its closure operators, e.g. each and eachWithIndex as well as the for .. in loop.

Results in the output:

Another example:

Results in:

The iterator pattern is also built in to other special operators such as the eachByte , eachFile , eachDir , eachLine , eachObject , eachMatch operators for working with streams, URLs, files, directories and regular expressions matches.

Loan my Resource Pattern

The Loan my Resource pattern ensures that a resource is deterministically disposed of once it goes out of scope.

This pattern is built in to many Groovy helper methods. You should consider using it yourself if you need to work with resources in ways beyond what Groovy supports.

Consider the following code which works with a file. First we might write some line to the file and then print its size:

We could also read back the contents of the file a line at a time and print each line out:

Note that normal Java Reader and PrintWriter objects were used under the covers by Groovy but the code writer did not have to worry about explicitly creating or closing those resources. The built-in Groovy methods loan the respective reader or writer to the closure code and then tidy up after themselves. So, you are using this pattern without having to do any work.

Sometimes however, you wish to do things slightly differently to what you can get for free using Groovy’s built-in mechanisms. You should consider utilising this pattern within your own resource-handling operations.

Consider how you might process the list of words on each line within the file. We could actually do this one too using Groovy’s built-in functions, but bear with us and assume we have to do some resource handling ourselves. Here is how we might write the code without using this pattern:

Notice that we now have an explicit call to close() in our code. If we didn’t code it just right (here we didn’t surround the code in a try …​ finally block, we run the risk of leaving the file handle open.

Let’s now apply the loan pattern. First, we’ll write a helper method:

Now, we can re-write our code as follows:

This is much simpler and has removed the explicit close() . This is now catered for in one spot so we can apply the appropriate level of testing or reviewing in just one spot to be sure we have no problems.

Using Monoids

Monoids allow the mechanics of an aggregation algorithm to be separated from the algorithm-specific logic associated with that aggregation. It is often thought to be a functional design pattern.

Perhaps, it is easiest seen with an example. Consider the code for integer sum, integer product and string concatenation. We might note various similarities:

Initialize an aggregate counter
Loop throw elements with for/while/iteration adjusting counter

We can remove the duplicate aggregation coding and the tease out the important differences for each algorithm. We might instead use Groovy’s inject method. This is a fold operation in functional programming jargon.

Here the first parameter is the initial value, and the supplied closure contains the algorithm-specific logic.

Similarly, for Groovy 3+, we can use the JDK stream API and lambda syntax as follows:

Looking at these examples, we might think all aggregation can be supported this way. In fact, we look for certain characteristics to ensure that this aggregation pattern will apply:

Closure: performing the aggregation step should produce a result of the same type as the elements being aggregated.

Examples: 1L + 3L produces a Long , and 'foo' + 'bar' produces a String . Non-monoid examples: 'foo'.size() + 'bar'.size() (takes strings, returns an integer), the type odd numbers with respect to addition, algorithms which don’t handle null arguments if such arguments are possible.

here, we simply mean closed under the operation, not the Groovy class.

Associativity: the order in which we apply the aggregation step should not matter.

Examples: (1 + 3) + 5 is the same as 1 + (3 + 5) , and ('a' + 'b') + 'c' is the same as 'a' + ('b' + 'c') . Non-monoid example: (10 - 5) - 3 is not equal to 10 - (5 - 3) therefore integers are not a monoid with respect to subtraction.

Identity element (sometimes also called a 'zero' element): there should be an element which aggregated with any element returns the original element.

Examples: 0 + 42 == 42 , 42 + 0 == 42 , 1 * 42 == 42 , and '' + 'foo' == 'foo' . Non-monoid example: the type non-empty strings is not a monoid with respect to concatenation.

If your algorithm doesn’t satisfy all the monoid properties, that doesn’t mean aggregation isn’t possible. It just means that you won’t get all the benefits from monoids, which we’ll cover shortly, or you might have a little more work to do. Also, you might be able to convert your data structures slightly to turn your problem into one involving monoids. We’ll cover that topic a little later in this section.

Consider adding the integers 10 through 16. Because the operation of addition for integers is a monoid, we already know that we can save writing code and instead use the approach we saw in the earlier inject examples. There are some other nice properties.

Because of the closure property, if we have a pairwise method like sum(Integer a, Integer b) , then for a monoid, we can always extend that method to work with a list, e.g. sum(List<Integer> nums) or sum(Integer first, Integer…​ rest) .

Because of associativity , we can employ some interesting ways to solve the aggregation including:

Divide and conquer algorithms which break the problem into smaller pieces

Various incremental algorithms for example memoization would allow summing from 1..5 to potentially start part way through be reusing a cached value of summing 1..4 if that had been calculated earlier

Inherent parallelization can make use of multiple cores

Let’s just look at the first of these in more detail. With a multicore processor, one core could add 10 plus 11 , another core 12 plus 13 , and so on. We’d use the identity element if needed (shown being added to 16 in our example). Then the intermediate results could also be added together concurrently and so on until the result was reached.

MonoidAddition

We have reduced the amount of code we need to write, and we also have potential performance gains.

Here is how we might code the previous example using the GPars concurrency and parallelism framework (two alternatives shown):

Suppose we want to find the average of the numbers 1..10. Groovy has a built-in method for this:

Now, suppose we want to build our own monoid solution instead of using the built-in version. It might seem difficult to find the identity element. After all:

Similarly, if we are tempted to write the pairwise aggregation closure it might be something like:

What b can we use for the identity element here so that our equation returns the original? We need to use a , but that isn’t a fixed value, so there is no identity .

Also, associativity doesn’t hold for this initial attempt at defining avg as these examples show:

Also, what about our closure property? Our original numbers were integers, but our average ( 5.5 ) is not. We can solve this by making our average work for any Number instances, but it might not always be this easy.

It might appear that this problem is not amenable to a monoidal solution. However, there are numerous ways to bring monoids into the solution.

We can split it into two parts:

The calculation of sum() can follow monoid rules and then our last step can calculate the average. We can even do a concurrent version with GPars:

Here, we were using the built-in sum() method (and sumParallel() for the GPars example), but if you were doing it by hand, the monoid nature of that part of your calculation would make it easier to write your own code for that step.

Alternatively, we can introduce a helper data structure that reworks the problem to be a monoid. Instead of just keeping the total, let’s keep a list containing the total and count of numbers. The code could look something like this:

Or, to be a little fancier, we could introduce a class for our data structure and even calculate concurrently:

Null Object Pattern

The Null Object Pattern involves using a special object place-marker object representing null. Typically, if you have a reference to null, you can’t invoke reference.field or reference.method() You receive the dreaded NullPointerException . The null object pattern uses a special object representing null, instead of using an actual null . This allows you to invoke field and method references on the null object. The result of using the null object should semantically be equivalent to doing nothing .

Suppose we have the following system:

When run, this prints out 1200 . Suppose now that we now invoke:

If we now try to calculate biggestSalary again, we receive a null pointer exception.

To overcome this problem, we can introduce a NullJob class and change the above statement to become:

This works as we require but it’s not always the best way to do this with Groovy. Groovy’s safe-dereference operator ( ?. ) operator and null aware closures often allow Groovy to avoid the need to create a special null object or null class. This is illustrated by examining a groovier way to write the above example:

Two things are going on here to allow this to work. First of all, max() is 'null aware' so that [300, null, 400].max() == 400. Secondly, with the ?. operator, an expression like p?.job?.salary will be equal to null if salary is equal to null, or if job is equal ` null or if p is equal to null. You don’t need to code a complex nested if ... then ... else to avoid a NullPointerException .

Consider the following example where we want to calculate size, cumulative sum and cumulative product of all the values in a tree structure.

Our first attempt has special logic within the calculation methods to handle null values.

If we introduce the null object pattern (here by defining the NullTree class), we can now simplify the logic in the size() , sum() and`product()` methods. These methods now much more clearly represent the logic for the normal (and now universal) case. Each of the methods within NullTree returns a value which represents doing nothing.

The result of running either of these examples is:

Note: a slight variation with the null object pattern is to combine it with the singleton pattern. So, we wouldn’t write new NullTree() wherever we needed a null object as shown above. Instead we would have a single null object instance which we would place within our data structures as needed.

Observer Pattern

The Observer Pattern allows one or more observers to be notified about changes or events from a subject object.

ObserverClasses

Here is a typical implementation of the classic pattern:

Using Closures, we can avoid creating the concrete observer classes as shown below:

As a variation for Groovy 3+, let’s consider dropping the Observer interface and using lambdas as shown below:

We are now calling the accept method from Consumer rather than the update method from Observer .

The JDK has some built-in classes which follow the observer pattern. The java.util.Observer and java.util.Observable classes are deprecated from JDK 9 due to various limitations. Instead, you are recommended to use various more powerful classes in the java.beans package such as java.beans.PropertyChangeListener . Luckily, Groovy has some built-in transforms ( groovy.beans.Bindable and groovy.beans.Vetoable ) which support for some key classes from that package.

Here, methods like addPropertyChangeListener perform the same role as registerObserver in previous examples. There is a firePropertyChange method corresponding to notifyAll / notifyObservers in previous examples but Groovy adds that automatically here, so it isn’t visible in the source code. There is also a propertyChange method that corresponds to the update method in previous examples, though again, that isn’t visible here.

Pimp my Library Pattern

The Pimp my Library Pattern suggests an approach for extending a library that nearly does everything that you need but just needs a little more. It assumes that you do not have source code for the library of interest.

Suppose we want to make use of the built-in Integer facilities in Groovy (which build upon the features already in Java). Those libraries have nearly all of the features we want but not quite everything. We may not have all of the source code to the Groovy and Java libraries so we can’t just change the library. Instead we augment the library. Groovy has a number of ways to do this. One way is to use a Category.

First, we’ll define a suitable category.

We have added two methods which augment the Integer methods by providing the greaterThanAll method. Categories follow conventions where they are defined as static methods with a special first parameter representing the class we wish to extend. The greaterThanAll(Integer self, others) static method becomes the greaterThanAll(other) instance method.

We defined two versions of greaterThanAll . One which works for collections, ranges etc. The other which works with a variable number of Integer arguments.

Here is how you would use the category.

As you can see, using this technique you can effectively enrich an original class without having access to its source code. Moreover, you can apply different enrichments in different parts of the system as well as work with un-enriched objects if we need to.

Proxy Pattern

The Proxy Pattern allows one object to act as a pretend replacement for some other object. In general, whoever is using the proxy, doesn’t realise that they are not using the real thing. The pattern is useful when the real object is hard to create or use: it may exist over a network connection, or be a large object in memory, or be a file, database or some other resource that is expensive or impossible to duplicate.

One common use of the proxy pattern is when talking to remote objects in a different JVM. Here is the client code for creating a proxy that talks via sockets to a server object as well as an example usage:

Here is what your server code might look like (start this first):

Singleton Pattern

The Singleton Pattern is used to make sure only one object of a particular class is ever created. This can be useful when exactly one object is needed to coordinate actions across a system; perhaps for efficiency where creating lots of identical objects would be wasteful, perhaps because a particular algorithm needing a single point of control is required or perhaps when an object is used to interact with a non-shareable resource.

Weaknesses of the Singleton pattern include:

It can reduce reuse. For instance, there are issues if you want to use inheritance with Singletons. If SingletonB extends SingletonA , should there be exactly (at most) one instance of each or should the creation of an object from one of the classes prohibit creation from the other. Also, if you decide both classes can have an instance, how do you override the getInstance() method which is static?

It is also hard to test singletons in general because of the static methods but Groovy can support that if required.

Suppose we wish to create a class for collecting votes. Because getting the right number of votes may be very important, we decide to use the singleton pattern. There will only ever be one VoteCollector object, so it makes it easier for us to reason about that objects creation and use.

Some points of interest in this code:

it has a private constructor, so no VoteCollector objects can be created in our system (except for the INSTANCE we create)

the INSTANCE is also private, so it can’t be changed once set

we haven’t made the updating of votes thread-safe at this point (it doesn’t add to this example)

the vote collector instance is not lazily created (if we never reference the class, the instance won’t be created; however, as soon as we reference the class, the instance will be created even if not needed initially)

We can use this singleton class in some script code as follows:

Here we used the instance 3 times. The second usage was even in a different thread (but don’t try this in a scenario with a new class loader).

Running this script yields (your hashcode value will vary):

Variations to this pattern:

To support lazy-loading and multi-threading, we could just use the synchronized keyword with the getInstance() method. This has a performance hit but will work.

We can consider variations involving double-checked locking and the volatile keyword, but see the limitations of this approach here .

Groovy’s meta-programming capabilities allow concepts like the singleton pattern to be enacted in a far more fundamental way. This example illustrates a simple way to use Groovy’s meta-programming capabilities to achieve the singleton pattern but not necessarily the most efficient way.

Suppose we want to keep track of the total number of calculations that a calculator performs. One way to do that is to use a singleton for the calculator class and keep a variable in the class with the count.

First we define some base classes. A Calculator class which performs calculations and records how many such calculations it performs and a Client class which acts as a facade to the calculator.

Now we can define and register a MetaClass which intercepts all attempts to create a Calculator object and always provides a pre-created instance instead. We also register this MetaClass with the Groovy system:

Now we use instances of our Client class from within a script. The client class will attempt to create new instances of the calculator but will always get the singleton.

Here is the result of running this script (your hashcode values may vary):

We can also implement the Singleton Pattern using Guice .

Consider the Calculator example again.

Guice is a Java-oriented framework that supports Interface-Oriented design. Hence we create a Calculator interface first. We can then create our CalculatorImpl implementation and a Client object which our script will interact with. The Client class isn’t strictly needed for this example but allows us to show that non-singleton instances are the default. Here is the code:

Note the @Inject annotation in the Client class. We can always tell right in the source code which fields will be injected.

In this example we chose to use an explicit binding. All of our dependencies (ok, only one in this example at the moment) are configured in the binding. The Guide injector knows about the binding and injects the dependencies as required when we create objects. For the singleton pattern to hold, you must always use Guice to create your instances. Nothing shown so far would stop you creating another instance of the calculator manually using new CalculatorImpl() which would of course violate the desired singleton behaviour.

In other scenarios (though probably not in large systems), we could choose to express dependencies using annotations, such as the following example shows:

Note the @Singleton annotation on the CalculatorImpl class and the @ImplementedBy annotation in the Calculator interface.

When run, the above example (using either approach) yields (your hashcode values will vary):

You can see that we obtained a new client object whenever we asked for an instance but it was injected with the same calculator object.

We can do the Calculator example again using Spring as follows:

And here is the result (your hashcode values will vary):

Simply Singleton

Use your singletons wisely

Double-checked locking and the Singleton pattern

Lazy Loading Singletons

Implementing the Singleton Pattern in C#

State Pattern

The State Pattern provides a structured approach to partitioning the behaviour within complex systems. The overall behaviour of a system is partitioned into well-defined states. Typically, each state is implemented by a class. The overall system behaviour can be determined firstly by knowing the current state of the system; secondly, by understanding the behaviour possible while in that state (as embodied in the methods of the class corresponding to that state).

Here is an example:

One of the great things about a dynamic language like Groovy though is that we can take this example and express it in many different ways depending on our particular needs. Some potential variations for this example are shown below.

One approach we could take is to leverage Interface-Oriented Design . To do this, we could introduce the following interface:

Then our Client , Online and 'Offline` classes could be modified to implement that interface, e.g.:

You might ask: Haven’t we just introduced additional boilerplate code? Can’t we rely on duck-typing for this? The answer is 'yes' and 'no'. We can get away with duck-typing but one of the key intentions of the state pattern is to partition complexity. If we know that the client class and each state class all satisfy one interface, then we have placed some key boundaries around the complexity. We can look at any state class in isolation and know the bounds of behaviour possible for that state.

We don’t have to use interfaces for this, but it helps express the intent of this particular style of partitioning and it helps reduce the size of our unit tests (we would have to have additional tests in place to express this intent in languages which have less support for interface-oriented design).

Alternatively, or in combination with other variations, we might decide to extract some of our State Pattern logic into helper classes. For example, we could define the following classes in a state pattern package/jar/script:

This is all quite generic and can be used wherever we want to introduce the state pattern. Here is what our code would look like now:

You can see here the startFrom and transitionTo methods begin to give our example code a DSL feel.

Alternatively, or in combination with other variations, we might decide to fully embrace a Domain Specific Language (DSL) approach to this example.

We can define the following generic helper functions (first discussed here ):

Now we can define and test our state machine like this:

This example isn’t an exact equivalent of the others. It doesn’t use predefined Online and Offline classes. Instead, it defines the entire state machine on the fly as needed. See the previous reference for more elaborate examples of this style.

See also: Model-based testing using ModelJUnit

Strategy Pattern

The Strategy Pattern allows you to abstract away particular algorithms from their usage. This allows you to easily swap the algorithm being used without having to change the calling code. The general form of the pattern is:

StrategyClasses

In Groovy, because of its ability to treat code as a first class object using anonymous methods (which we loosely call Closures ), the need for the strategy pattern is greatly reduced. You can simply place algorithms inside Closures.

First let’s look at the traditional way of encapsulating the Strategy Pattern.

Here we have defined an interface Calc which our concrete strategy classes will implement (we could also have used an abstract class). We then defined two algorithms for doing simple multiplication: CalcByMult the normal way, and CalcByManyAdds using only addition (don’t try this one using negative numbers - yes we could fix this but it would just make the example longer). We then use normal polymorphism to invoke the algorithms.

Here is the Groovier way to achieve the same thing using Closures:

For Groovy 3+, we can leverage lambda syntax:

Or we can use the built-in JDK BiFunction class:

Template Method Pattern

The Template Method Pattern abstracts away the details of several algorithms. The generic part of an algorithm is contained within a base class. Particular implementation details are captured within child classes. The generic pattern of classes involved looks like this:

TemplateMethodClasses

In this example, the base Accumulator class captures the essence of the accumulation algorithm. The child classes Sum and Product provide particular customised ways to use the generic accumulation algorithm.

In this particular case, you could use Groovy’s inject method to achieve a similar result using Closures:

Thanks to duck-typing, this would also work with other objects which support an add ( plus() in Groovy) method, e.g.:

We could also do the multiplication case as follows (re-writing as a one-liner):

Using closures this way looks like the Strategy Pattern , but if we realise that Groovy’s inject method is the generic part of the algorithm for our template method, then the Closures become the customised parts of the template method pattern.

For Groovy 3+, we can use lambda syntax as an alternative to the closure syntax:

Here the stream api’s reduce method is the generic part of the algorithm for our template method, and the lambdas are the customised parts of the template method pattern.

Visitor Pattern

The Visitor Pattern is one of those well-known but not often used patterns. Perhaps this is because it seems a little complex at first. But once you become familiar with it, it becomes a powerful way to evolve your code and as we’ll see, Groovy provides ways to reduce some to the complexity, so there is no reason not to consider using this pattern.

The goal of the pattern is to separate an algorithm from an object structure. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures.

This example considers how to calculate the bounds of shapes (or collections of shapes). Our first attempt uses the traditional visitor pattern. We will see a more Groovy way to do this shortly.

That took quite a bit of code, but the idea now is that we could add further algorithms just by adding new visitors with our shape classes remaining unchanged, e.g. we could add a total area visitor or a collision detection visitor.

We can improve the clarity of our code (and shrink it to about half the size) by making use of Groovy Closures as follows:

Or, using lambdas as follows:

Advanced Example

Let’s consider another example to illustrate some more points about this pattern.

If we now use NodeType1Counter on a tree like this:

Then we have one NodeType1 object as root and one of the children is also a NodeType1 instance. The other child is a NodeType2 instance. That means using NodeType1Counter here should count 2 NodeType1 objects as the last statement verifies.

This example illustrates some of the advantages of the visitor pattern. For example, while our visitor has state (the count of NodeType1 objects), the tree of objects itself is not changed. Similarly, if we wanted to have a visitor counting all node types, or one that counts how many different types are used, or one that gathers information using methods special to the node types, again, the visitor alone is all that would need to be written.

In this case we might have a fair bit of work to do. We probably have to change the Visitor interface to accept the new type, and change potentially most existing visitors based on that interface change, and we have to write the new type itself. A better approach is to write a default implementation of the visitor which all concrete visitors will extend. We’ll see this approach in use shortly.

Then you have a problem. Since the node describes how to iterate, you have no influence and stop iteration at a point or change the order. So maybe we should change this a little to this:

Some small changes but with big effect. The visitor is now recursive and tells me how to iterate. The implementation in the Nodes is minimized to visitor.visit(this) , DefaultVisitor is now able to catch the new types, we can stop iteration by not delegating to super. Of course the big disadvantage now is that it is no longer iterative, but you can’t get all the benefits.

The question now is how to make that a bit more Groovy. Didn’t you find this visitor.visit(this) strange? Why is it there? The answer is to simulate double dispatch. In Java, the compile time type is used, so for visitor.visit(children[i]) the compiler won’t be able to find the correct method, because Visitor does not contain a method visit(Visitable) . And even if it would, we would like to visit the more special methods with NodeType1 or NodeType2 .

Now Groovy is not using the static type, Groovy uses the runtime type. This means we can use visitor.visit(children[i]) without any problem. Since we minimized the accept method to just do the double dispatch part and since the runtime type system of Groovy will already cover that, do we need the accept method? Not really, but we can do even more. We had the disadvantage of not knowing how to handle unknown tree elements. We had to extend the interface Visitor for that, resulting in changes to DefaultVisitor and then we have the task to provide a useful default like iterating the node or not doing anything at all. Now with Groovy we can catch that case by adding a visit(Visitable) method that does nothing. That would be the same in Java btw.

But don’t let us stop here. Do we need the Visitor interface? If we don’t have the accept method, then we don’t need the Visitor interface at all. So the new code would be:

Looks like we saved a few lines of code here, but we made more. The Visitable nodes now do not refer to any Visitor class or interface. This is about the best level of separation you might expect here, but we can go further. Let’s change the Visitable interface a little and let it return the children we want to visit next. This allows us a general iteration method.

DefaultVisitor now looks a bit different. It has a doIteration method that will get the children it should iterate over and then call visit on each element. Per default this will call visit(Visitable) which then iterates over the children of this child. Visitable has also changed to ensure that any node will be able to return children (even if empty). We didn’t have to change the NodeType1 and NodeType2 class, because the way the children field was defined already made them a property, which means Groovy is so nice to generate a get method for us. Now the really interesting part is NodeType1Counter , it is interesting because we have not changed it. super.visit(n1) will now call visit(Visitable) which will call doIteration which will start the next level of iteration. So no change. But visit(it) will call visit(NodeType1) if it is of type NodeType1 . In fact, we don’t need the doIteration method, we could do that in visit(Visitable) too, but this variant has some benefits. It allows us to write a new Visitor that overwrites visit( Visitable ) for error cases which of course means we must not do super.visit(n1) but doIteration(n1) .

In the end we got ~40% less code, a robust and stable architecture, and we completely removed the Visitor from the Visitable. To achieve the same in Java, you would probably need to resort to reflection.

The visitor pattern has sometimes been described as a poor fit for extreme programming techniques because you need to make changes to so many classes all the time. With our design, if we add new types we don’t need to change anything. So, the pattern is a good fit for agile approaches when using Groovy.

There are variants of the Visitor pattern, like the acyclic visitor pattern , that try to solve the problem of adding new node types with special visitors. The implementations of these visitors have their own code smells, like using casts, overuse of instanceof , and other tricks. What’s more the problems such approaches are trying to solve don’t occur within the Groovy version. We recommend avoiding that variant of this pattern.

Finally, in case it isn’t obvious, NodeType1Counter could be implemented in Java as well. Groovy will recognize the visit methods and call them as needed because DefaultVisitor is still Groovy and does all the magic.

Componentization: the Visitor example

Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (1995). Design Patterns: Elements of Reusable Object-Oriented Software . Addison-Wesley. ISBN 0-201-63361-2.

The canonical reference of design patterns.

Martin Fowler (1999). Refactoring: Improving the Design of Existing Code . Addison-Wesley. ISBN 0-201-48567-2.

Joshua Kerievsky (2004). Refactoring To Patterns . Addison-Wesley. ISBN 0-321-21335-1.

Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates (2004). Head First Design Patterns . O’Reilly. ISBN 0-596-00712-4. * A great book to read, informative as well as amusing.

Dierk Koenig with Andrew Glover, Paul King, Guillaume Laforge and Jon Skeet (2007). Groovy in Action . Manning. ISBN 1-932394-84-2.

Discusses Visitor, Builder and other Patterns.

Brad Appleton (1999). Pizza Inversion - a Pattern for Efficient Resource Consumption .

One of the most frequently used patterns by many software engineers!

Design Patterns in Dynamic Languages by Neil Ford. Design Patterns in Dynamic Languages .

4. Acknowledgements

The Groovy team would like to thank the contributors of this documentation (in alphabetical order of last/surname):

Dmitry Andreychuk

Hamlet D’Arcy

Aseem Bansal

Andrey Bloschetsov

Jeff Scott Brown

Cédric Champeau

Tobia Conforto

Dimitar Dimitrov

Andrew Eisenberg

Marcin Erdmann

Christoph Frick

Mario García

David Michael Karr

Guillaume Laforge

Peter Ledbrook

Grant McConnaughey

Eric Milles

David Nahodil

James Northrop

Marc Paquette

Michael Schuenck

Pascal Schumacher

Maksym Stavytskyi

André Steingreß

Edinson Padrón Urdaneta

Keegan Witt

This work is licensed under the Apache License, Version 2.0 .

Monday, February 12, 2018

Groovy: basic concepts: variables, storage and commands, simple variables, composite variables, copy and reference, assignments, sequential commands, conditional commands, switch-case, iterative commands, each and eachwithindex, expressions with side effects, no comments:.

Post a Comment

Logo haki

May 20, 2010

Groovy goodness: multiple assignments revisited.

Multiple assignments in Groovy is something already covered before in the Groovy Goodness series. But today at the Gr8Conf I got some extra information about it's possibilities. First of all we can use type information in the multiple assignment. So we can assign the returning values to typed variables. The next thing is we can use multiple assignments basically for anything with a getAt method. And this works also for our own classes, we only have to provide an implementation for the getAt method.

Toolify logo

The Latest AIs, every day

AIs with the most favorites on Toolify

AIs with the highest website traffic (monthly visits)

AI Tools by browser extensions

AI Tools by Apps

Discover the Discord of AI

Top AI lists by month and monthly visits.

Top AI lists by category and monthly visits.

Top AI lists by region and monthly visits.

Top AI lists by source and monthly visits.

Top AI lists by revenue and real traffic.

Master Variables in Groovy with this Beginner Tutorial

Updated on Dec 11,2023

Table of Contents

  • Introduction

Defining Variables in Groovy

Naming variables in groovy, dynamic typing in groovy, multiple assignments in groovy, using data types in groovy variables, printing variables in groovy, difference between single quotes and double quotes in print, case sensitivity in variable names, changing variable types in groovy.

Groovy is a versatile scripting language that allows for the easy creation and manipulation of variables. In this section, we will explore how to define variables in Groovy and some of their key features.

To define a variable in Groovy, the keyword "def" is used followed by the variable name and an optional assignment of a value. For example, we can define a variable called "name" and assign it the value "Raghav" like this:

By using the "def" keyword, Groovy automatically infers the data Type of the variable Based on the assigned value. However, it is considered a good practice to explicitly specify the data type for better Clarity . For example, we can define a variable as a STRING like this:

Once a variable is defined, it can be printed using the println statement followed by the variable name. For example:

This will output the value of the variable "name" to the console.

  • Easy and flexible variable definition
  • Unnecessary to specify data types, as Groovy infers them automatically
  • Can assign values to variables in a single line
  • May lead to confusion if variable types are not explicitly specified
  • Limited enforcement of variable naming conventions, potentially leading to naming conflicts

In Groovy, variable names can be composed of letters, digits, and underscores. However, there are some conventions to keep in mind:

  • Variable names should start with a letter or an underscore.
  • Variable names are case-sensitive, so "name" and "Name" refer to two different variables.
  • Descriptive and Meaningful variable names are encouraged to improve code readability.

For example, we can define variables with names like "age", "email_address", or "total_sales" to represent various data in our Groovy script.

  • Allows for descriptive and meaningful variable names
  • Provides flexibility in variable naming conventions
  • Lack of strict enforcement may lead to naming conflicts or confusion

One of the key features of Groovy is its support for dynamic typing. This means that the type of a variable is resolved at runtime, allowing for more flexibility in handling values and their types.

Unlike languages such as Java or C, where variables are statically Typed and their types need to be declared explicitly, Groovy allows for implicit typing. This means that the type of a variable is determined by the value assigned to it, without the need for explicit type declarations.

For example, we can assign different types of values to the same variable in Groovy:

In this example, the variable "variable" can hold a string, an integer, or a floating-point number at different points in the script.

  • Increased flexibility in assigning and handling variable types
  • Simplifies code and reduces the need for explicit type declarations
  • May introduce unexpected errors if variable types are changed dynamically
  • Requires careful consideration and Attention to variable types throughout the script

In Groovy, it is possible to assign multiple values to multiple variables in a single line. This feature is known as multiple assignments and can be useful in various scenarios.

To perform multiple assignments in Groovy, the values are enclosed in square brackets and separated by commas. The variables to be assigned the values are listed in parentheses. For example:

In this example, the values 10, 20, and 30 are assigned to variables a, b, and c, respectively.

Multiple assignments can also be combined with different data types. For example:

In this case, the values "John Doe", 25, and 70.5 are assigned to variables name, age, and weight, respectively.

  • Allows for concise assignment of multiple values to multiple variables
  • Simplifies code and reduces the number of lines needed for assignments
  • May be less readable when multiple assignments contain many variables and values
  • Requires careful consideration of the order and number of variables and values

In Groovy, variables can hold values of different data types. By assigning a specific data type to a variable, we can ensure that it stores values of that particular type.

Groovy supports common data types such as:

  • Integer: whole numbers without decimal places.
  • Double: floating-point numbers with decimal places.
  • String: a sequence of characters.
  • Boolean: true or false values.

To explicitly assign a data type to a variable in Groovy, we can use the following syntax:

For example, if we want to assign an integer value to a variable:

In this case, the variable "age" is explicitly assigned the data type "Integer".

By using data types in Groovy variables, we can ensure type safety and avoid errors caused by incorrect value assignments.

  • Provides type safety by ensuring variables store values of the specified data type
  • Improves code clarity and reduces the likelihood of errors
  • Requires additional syntax to explicitly assign data types
  • May make the code slightly more verbose

Printing variable values is an essential aspect of any programming language, as it allows us to see the Current state of variables and perform debugging tasks.

In Groovy, variable values can be printed using the println statement followed by the variable name. For example:

In addition to println , Groovy also provides the print statement, which prints the value without a line break. For example:

This will output the value of the variable "age" without a line break.

  • Allows for easy debugging and monitoring of variable values
  • Provides quick visibility into the state of variables during script execution
  • Lacks advanced formatting options for variable printing
  • May clutter the console output if used excessively

In Groovy, there is a difference between using single quotes ('') and double quotes ("") when printing variables or combining them with strings.

When using single quotes, the text is treated as a literal string, and variable names are not resolved or replaced with their corresponding values. For example:

In this case, the variable "$name" is treated as a literal string and not replaced with the value of the variable.

On the other HAND , when using double quotes, Groovy interprets the text and resolves variable names to their corresponding values. For example:

In this case, the variable "$name" is replaced with its value, resulting in the output "My name is John Doe".

  • Provides flexibility in combining variables with strings for dynamic output
  • Offers a choice between literal string printing and variable value printing
  • May introduce complexity or confusion if proper quoting is not used
  • Requires attention to Detail when using variables within strings to ensure correct output

In Groovy, variable names are case-sensitive, meaning that uppercase and lowercase letters are treated as distinct characters. This means that variables with different capitalization are considered different variables.

For example, if we define two variables named "age" and "Age":

In this case, "age" and "Age" are two separate variables, each holding a different value.

When referencing variables, it is important to use the correct capitalization. Referencing a variable with incorrect capitalization will result in an error or unexpected behavior.

  • Allows for distinct variables with different capitalization
  • Supports flexibility in variable naming conventions
  • May lead to confusion or errors if proper capitalization is not used
  • Requires consistent and careful attention to variable names throughout the script

One of the unique features of Groovy is its dynamic typing, which allows changing the type of a variable even after it has been defined. This means that a variable can hold values of different types during the execution of a script.

For example, we can define a variable as a string and later assign it a numeric value:

In this case, the variable "variable" initially holds the value "Hello" as a string. However, it can be reassigned to the value 10, which is an integer.

Groovy's dynamic typing provides flexibility but also requires caution. It is important to ensure that variables are used consistently with their intended types to avoid unexpected behavior or errors.

  • Enables flexibility and adaptability in variable usage
  • Simplifies development by allowing changes to variable types without explicit type declarations
  • May introduce errors or unexpected behavior if variable types are changed inconsistently
  • Requires careful consideration and adherence to variable types throughout the script

The above is a brief introduction to Master Variables in Groovy with this Beginner Tutorial

Let's move on to the first section of Master Variables in Groovy with this Beginner Tutorial

Find AI tools in Toolify

Join TOOLIFY to find the ai tools

Get started

  • Discover Leanbe: Boost Your Customer Engagement and Product Development
  • Unlock Your Productivity Potential with LeanBe
  • Unleash Your Naval Power! Best Naval Civs in Civilization 5 - Part 7
  • Master Algebra: Essential Guide for March SAT Math
  • Let God Lead and Watch Your Life Transform | Inspirational Video
  • Magewell XI204XE SD/HD Video Capture Card Review
  • Discover Nepal's Ultimate Hiking Adventure
  • Master the Art of Debugging with Our Step-by-Step Guide
  • Maximize Customer Satisfaction with Leanbe's Feedback Tool
  • Unleashing the Power of AI: A Closer Look
  • Transform Your Images with Microsoft's BING and DALL-E 3
  • Create Stunning Images with AI for Free!
  • Unleash Your Creativity with Microsoft Bing AI Image Creator
  • Create Unlimited AI Images for Free!
  • Discover the Amazing Microsoft Bing Image Creator
  • Create Stunning Images with Microsoft Image Creator
  • AI Showdown: Stable Diffusion vs Dall E vs Bing Image Creator
  • Create Stunning Images with Free Ai Text to Image Tool
  • Unleashing Generative AI: Exploring Opportunities in QE&T
  • Create a YouTube Channel with AI: ChatGPT, Bing Image Maker, Canva
  • Google's AI Demo Scandal Sparks Stock Plunge
  • Unveiling the Yoga Master: the Life of Tirumalai Krishnamacharya
  • Hilarious Encounter: Jimmy's Unforgettable Moment with Robert Irwin
  • Google's Incredible Gemini Demo: Unveiling the Future
  • Say Goodbye to Under Eye Dark Circles - Simple Makeup Tips
  • Discover Your Magical Soul Mate in ASMR Cosplay Role Play
  • Boost Kidney Health with these Top Foods
  • OpenAI's GEMINI 1.0 Under Scrutiny
  • Unveiling the Mind-Blowing Gemini Ultra!
  • Shocking AI News: Google's Deception Exposed!
  • Unveiling AMD's Ryzen 4000: Performance Revolution
  • Unlock Massive Performance Gains with Asynchronous Compute
  • Intel's Alder Lake: Revolutionary Advancements Unveiled
  • Install Official AMD Drivers on ASUS Rockal
  • Intel 11th Gen CPUs: Benchmarks & Features Compared
  • Intel Core i9 11900K vs i7 11700K: Choose Wisely!
  • Unlock Maximum Performance with Asus ROG Strix X670E-F and Precision Boost Overdrive
  • Unleash Extraordinary Gaming Performance with the ASUS TUF Gaming A16 Advantage Edition
  • Boost Workstation Performance with AMD RapidFire API
  • Discover ASUS Tough Gaming Laptops

Effortlessly Generate Floor Plans with Plan FinderTable of Contents Introduction Understanding the

From Pro Boxer to Vegetative State: The Untold Story of Prichard ColonTable of Contents Introductio

Mastering Pencil Cactus Care: Unlock the 7 Secrets of Growth and Propagation!Table of Contents Intr

toolify

The Best AI Websites & AI Tools Directory

  • Most Saved AIs
  • Most Used AIs
  • AI Browser Extensions
  • Discord of AI
  • Top AI By Monthly
  • Top AI By Categories
  • Top AI By Regions
  • Top AI By Source
  • Top AI by Revenue
  • More Business
  • Stable Video Diffusion
  • Top AI Tools
  • Privacy Policy
  • [email protected]
  • architecture
  • parafrasear
  • Character AI
  • subtitle videos
  • Mapa mental

Copyright ©2024 toolify

Programming Groovy 2 by

Get full access to Programming Groovy 2 and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Using Multiple Assignments

Passing multiple arguments to methods is commonplace in many programming languages. Returning multiple results from functions, on the other hand, is not that common, though it can be quite convenient. We can return multiple results from functions and assign them to multiple variables in one shot. Simply return an array and use comma-separated variables wrapped in parentheses on the left side of the assignment.

In the next example, we have a function that splits a full name into first and last names. The split function, as we’d expect, returns an array. We can assign the result of the splitName function to a pair of variables: firstName and lastName . Groovy assigns the two values to the two variables, respectively. ...

Get Programming Groovy 2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

groovy multiple variable assignment

OGICBIG
Tutorials
  • Send Message
  • Core Java Tutorials
  • Java EE Tutorials
  • Java Swing Tutorials
  • Spring Framework Tutorials
  • Unit Testing
  • Build Tools
  • Misc Tutorials

Groovy supports all Java types (primitive and reference types).

All primitives types are auto converted to their wrapper types. So int a = 2 will become Integer a = 2.

When declaring variables we can do one of the followings:

(that will create a local variable):

When no type is used, variables act like they are of type Object, so they can be reassigned to different types:

Variables with no type are global so they can be accessed across methods.

The code outside methods but still in the script is copied to method ( ), so during runtime everything is inside methods. In that sense, this feature allows the variables declared in a method to be accessible to other methods.

Groovy keeps these global variables in a map like object ( ).

When is used, variables act like they are of type Object, so they can be reassigned to different types (same as when no type is used):

Variables declared with are local, so they cannot be accessed across methods:


groovy.lang.MissingPropertyException: No such property: a for class: DefExample2
at DefExample2.printVars(DefExample2.groovy:3)
at DefExample2.run(DefExample2.groovy:6)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

They follow strict typing rules (just like Java). So they cannot be reassigned to different types:


Caught: org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'apple' with class 'java.lang.String' to class 'int'
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'apple' with class 'java.lang.String' to class 'int'
at ActualTypeExample.run(ActualTypeExample.groovy:3)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

Like variables they are also local, so they cannot be accessed across methods.


groovy.lang.MissingPropertyException: No such property: a for class: ActualTypeExample2
at ActualTypeExample2.printVars(ActualTypeExample2.groovy:3)
at ActualTypeExample2.run(ActualTypeExample2.groovy:6)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

As seen above, Groovy uses Objects for everything (int is printed as ). Primitives are auto converted to their wrapper type.

In Java it is not even possible to use on primitives:

(); //error: Cannot resolve method 'getClass()'

In Groovy, all variables are initialized (even local) with their default values (just like instance variable).

In Java, if we try to use a local variable without initializing:

); //error: variable a might not have been initialized }

Regarding types, we have all three above options to use for method parameters, but return type must be the actual type or :

Dependencies and Technologies Used:

ui-button ui-button Data Type and Declaring Variables
  • ActualTypeExample.groovy
  • ActualTypeExample2.groovy
  • DefExample.groovy
  • DefExample2.groovy
  • DefaultValues.groovy
  • MethodParamAndReturn.groovy
  • MethodParamAndReturn2.groovy
  • MethodParamAndReturn3.groovy
  • MethodParamAndReturn4.groovy
  • NoPrimitivesExample.groovy
  • NoTypeExample.groovy
  • NoTypeExample2.groovy

Closures in Groovy

Last updated: February 13, 2024

groovy multiple variable assignment

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema .

The way it does all of that is by using a design model , a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

>> Take a look at DBSchema

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June , after which it will permanently increase by 50$

>> GET ACCESS NOW

Azure Spring Apps is a fully managed service from Microsoft (built in collaboration with VMware), focused on building and deploying Spring Boot applications on Azure Cloud without worrying about Kubernetes.

The Enterprise plan comes with some interesting features, such as commercial Spring runtime support, a 99.95% SLA and some deep discounts (up to 47%) when you are ready for production.

>> Learn more and deploy your first Spring Boot app to Azure.

And, you can participate in a very quick (1 minute) paid user research from the Java on Azure product team.

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only , so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server's performance, with most of the profiling work done separately - so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server , hit the record button, and you'll have results within minutes:

>> Try out the Profiler

A quick guide to materially improve your tests with Junit 5:

Do JSON right with Jackson

Download the E-book

Get the most out of the Apache HTTP Client

Get Started with Apache Maven:

Get started with Spring and Spring Boot, through the reference Learn Spring course:

>> LEARN SPRING

Building a REST API with Spring?

The AI Assistant to boost Boost your productivity writing unit tests - Machinet AI .

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code. And, the AI Chat crafts code and fixes errors with ease, like a helpful sidekick.

Simplify Your Coding Journey with Machinet AI :

>> Install Machinet AI in your IntelliJ

Get non-trivial analysis (and trivial, too!) suggested right inside your IDE or Git platform so you can code smart, create more value, and stay confident when you push.

Get CodiumAI for free and become part of a community of over 280,000 developers who are already experiencing improved and quicker coding.

Write code that works the way you meant it to:

>> CodiumAI. Meaningful Code Tests for Busy Devs

Looking for the ideal Linux distro for running modern Spring apps in the cloud?

Meet Alpaquita Linux : lightweight, secure, and powerful enough to handle heavy workloads.

This distro is specifically designed for running Java apps . It builds upon Alpine and features significant enhancements to excel in high-density container environments while meeting enterprise-grade security standards.

Specifically, the container image size is ~30% smaller than standard options, and it consumes up to 30% less RAM:

>> Try Alpaquita Containers now.

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth , to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project .

You can explore the course here:

>> Learn Spring Security

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

In this Introductory tutorial, we’ll explore the concept of closures in Groovy , a key feature of this dynamic and powerful JVM language.

Many other languages, including Javascript and Python, support the concept of closures. However, the characteristics and functioning of closures vary from language to language.

We’ll touch on key aspects of Groovy closures, showing examples of how they are used along the way.

2. What Is a Closure?

A closure is an anonymous block of code. In Groovy, it is an instance of the Closure class . Closures can take 0 or more parameters and always return a value.

Additionally, a closure may access surrounding variables outside its scope and use them — along with its local variables — during execution.

Furthermore, we can assign a closure to a variable or pass it as a parameter to a method. Therefore, a closure provides functionality for delayed execution.

3. Closure Declaration

A Groovy Closure contains parameters, the arrow ->, and the code to execute. Parameters are optional and, when provided, are comma-separated.

3.1. Basic Declaration

Here, the closure printWelcome prints a statement when invoked. Now, let’s write a quick example of a unary closure:

Here, the closure print takes one parameter — name — and prints it when invoked.

Since the definition of a closure looks similar to a method , let’s compare them:

Here, the method and the corresponding closure behave similarly. However, there are subtle differences between a closure and a method, which we’ll discuss later in the Closures vs Methods section.

3.2. Execution

We can execute a closure in two ways — we can invoke it like it were any other method, or we can use the call method.

For instance, as a regular method:

And executing with the call method:

4. Parameters

The parameters of Groovy closures are similar to those of regular methods.

4.1. Implicit Parameter

We can define a unary closure without a parameter because when parameters are not defined, Groovy assumes an implicit parameter named “ it” :

4.2. Multiple Parameters

Here’s a closure that takes two parameters and returns the result of multiplying them:

4.3. Parameter Types

In the examples so far, there has been no type provided with our parameters. We can also set the type of closure parameters. For instance, let’s rewrite the multiply method to consider other operations:

4.4. Varargs

We can declare a variable number of arguments in closures, similar to regular methods. For example:

5. A Closure as an Argument

We can pass a Closure as an argument to a regular Groovy method. This allows the method to call our closure to complete its task, allowing us to customize its behavior.

Let’s discuss a simple use-case: the calculation of the volume of regular figures.

In this example, the volume is defined as area multiplied by height. However, calculation of area can vary for different shapes.

Therefore, we’ll write the volume method, which takes a closure areaCalculator as an argument, and we’ll pass the implementation of the area calculation during invocation:

Let’s find a volume of a cone using the same method:

6. Nested Closures

We can declare and invoke closures inside a closure.

For instance, let’s add a logging ability to the already discussed calculate closure:

7. Lazy Evaluation of Strings

Groovy String s are usually evaluated and interpolated at the time of creation. For instance:

Even if we modify the value of the name variable, the welcomeMsg is not going to change:

Closure interpolation allows us to provide lazy evaluation of String s , recalculated from the current values around them. For example:

Only this time, changing the variable affects the interpolated string’s value as well:

8. Closures in Collections

Groovy Collections use closures in many of their APIs. For example, let’s define a list of items and print them using the unary closure each , which has an implicit parameter:

Often, based on some criterion, we may need to create a list from a map. For instance:

9. Closures vs Methods

So far, we’ve seen the syntax, execution, and parameters of closures, which are fairly similar to methods. Let’s now compare closures with methods.

Unlike a regular Groovy method:

  • We can pass a Closure as an argument to a method
  • Unary closures can use the implicit it parameter
  • We can assign a Closure to a variable and execute it later, either as a method or with call
  • Groovy determines the return type of the closures at runtime
  • We can declare and invoke closures inside a closure
  • Closures always return a value

Hence, closures have benefits over regular methods and are a powerful feature of Groovy.

10. Conclusion

In this article, we’ve seen how to create closures in Groovy and explored how they are used.

Closures provide an effective way to inject functionality into objects and methods for delayed execution.

As always, the code and unit tests from this article are available over on GitHub .

Creating PDFs is actually surprisingly hard. When we first tried, none of the existing PDF libraries met our needs. So we made DocRaptor for ourselves and later launched it as one of the first HTML-to-PDF APIs.

We think DocRaptor is the fastest and most scalable way to make PDFs , especially high-quality or complex PDFs. And as developers ourselves, we love good documentation, no-account trial keys, and an easy setup process.

>> Try DocRaptor's HTML-to-PDF Java Client (No Signup Required)

Slow MySQL query performance is all too common. Of course it is.

The Jet Profiler was built entirely for MySQL , so it's fine-tuned for it and does advanced everything with relaly minimal impact and no server changes.

Explore the secure, reliable, and high-performance Test Execution Cloud built for scale. Right in your IDE:

Basically, write code that works the way you meant it to.

AI is all the rage these days, but for very good reason. The highly practical coding companion, you'll get the power of AI-assisted coding and automated unit test generation . Machinet's Unit Test AI Agent utilizes your own project context to create meaningful unit tests that intelligently aligns with the behavior of the code.

Build your API with SPRING - book cover

MarketSplash

Getting To Know Groovy Variables And Their Functions

Groovy variables offer flexibility and simplicity, making coding more efficient. In this article, we'll explore the nuances of Groovy's variable types, their scopes, and best practices to optimize your code. Whether you're new to Groovy or seeking a refresher, this guide is for you.

💡 KEY INSIGHTS

  • Variable declaration in Groovy can be dynamic with `def` or static, offering flexibility in typing.
  • Scope of variables in Groovy includes local, instance, and class variables, each with unique characteristics.
  • Groovy supports immutable variables using `final`, ensuring constant values throughout the code.
  • Understanding variable scope and naming conventions is crucial for writing clean, maintainable Groovy code.

Groovy , a popular scripting language for the Java platform, offers a unique approach to variable declaration and usage. With its concise syntax and flexibility, understanding Groovy variables can enhance your coding efficiency.

Let's explore the nuances and best practices of working with them.

groovy multiple variable assignment

Understanding Groovy Variables

Types of groovy variables, declaring and initializing variables, variable scope in groovy, best practices for using variables, frequently asked questions.

Groovy, being a dynamic language, offers a flexible approach to variable declaration. Unlike statically-typed languages, Groovy allows you to declare variables without specifying their type. This feature can simplify code and enhance readability.

In Groovy, you can declare a variable using the def keyword, making it dynamically typed. This means the variable's type is determined at runtime based on the value it holds.

However, if you prefer, you can still use static typing by specifying the type during declaration:

When declaring a variable in Groovy, you can either initialize it immediately or leave it uninitialized. An uninitialized variable will have a default value of null .

Groovy has three main scopes for variables: local, instance, and class. Local variables are declared within methods and are only accessible within that method.

Instance variables belong to an instance of a class, while class variables (often called static variables) belong to the class itself.

Frequently Used Variable Types

Groovy supports various data types for variables. Some of the commonly used types include:

  • String : Represents textual data.
  • int : Represents integer values.
  • boolean : Represents true or false values.
  • List : Represents a collection of items.

For instance, to declare a list:

In Groovy, variables can be categorized based on their declaration and scope. Understanding these types is crucial for effective coding in Groovy, as each type has its own characteristics and use cases.

Local variables are declared within methods or blocks of code. They are temporary and only exist during the execution of the method or block. Once the method completes, these variables are discarded.

Instance variables are declared within a class but outside any method. They belong to an instance of the class and hold values that are specific to that instance.

Class variables , often referred to as static variables, are associated with the class itself rather than any specific instance. They are declared using the static keyword.

One of the unique features of Groovy is its support for dynamic variables . These are variables that are not declared in a class but can be added to an object at runtime.

Groovy supports both typed and untyped variables . While typed variables have a specific data type assigned during declaration, untyped variables use the def keyword.

Groovy also supports immutable variables using the final keyword. Once assigned a value, these variables cannot be reassigned.

Whether you're working with local, instance, class, or dynamic variables, Groovy offers flexibility and power in variable declaration and usage.

In Groovy, the process of declaring and initializing variables is straightforward, yet offers flexibility. This section will guide you through the essentials of variable declaration and initialization in Groovy.

To declare a variable in Groovy, you can either specify its type or use the def keyword for dynamic typing. The def keyword tells Groovy that the variable's type will be determined at runtime.

After declaring a variable, you can assign a value to it. If you don't, the default value for most variables is null .

Groovy allows for the simultaneous declaration of multiple variables of the same type, making your code more concise.

In Groovy, as in many programming languages, the scope of a variable defines the part of the code where the variable can be accessed and modified. Grasping the concept of variable scope is essential for writing clean and error-free Groovy scripts.

Local variables are declared within methods, closures, or loops. Their scope is limited to the block of code where they are defined, making them inaccessible outside of it.

Instance variables are declared within a class but outside any specific method or block. They are associated with an instance of the class, and their values can vary between different instances.

Class variables , also known as static variables, are associated with the class itself rather than its instances. They are shared among all instances of the class and are declared using the static keyword.

Groovy's dynamic nature allows for the addition of variables to an object at runtime. These dynamic variables have a scope limited to the object they are added to.

Understanding variable scope helps in preventing common mistakes like variable shadowing, where a local variable has the same name as an instance or class variable.

It's advisable to choose descriptive variable names and be aware of the scope to avoid such conflicts.

In Groovy, being aware of variable scope ensures that variables are used correctly and efficiently, leading to more maintainable and bug-free code.

When working with Groovy, or any programming language, adhering to best practices for variable usage can make your code more readable, maintainable, and less prone to errors. Here are some recommended guidelines for using variables in Groovy.

Best Practice Description
Descriptive Variable Names Opt for variable names that clearly convey the purpose or nature of the data they hold, enhancing code readability
Avoid Global Variables Instead of global variables, use local or instance variables to reduce potential conflicts and enhance modularity
Use final for Constants Utilize the final keyword for variables that shouldn't change, ensuring their values remain constant throughout the code
Limit Variable Scope Declare variables within the smallest possible scope, reducing chances of unintended modifications and making the code cleaner
Avoid Variable Shadowing Ensure local variables don't share names with instance or class variables to prevent confusion and potential errors
Initialize Variables Assign initial values to variables upon declaration to prevent unexpected behavior, especially since uninitialized variables default to null in Groovy
Type Safety While Groovy is dynamically typed, specifying the type when context demands can help in early detection of type-related errors

By following these best practices, you'll ensure that your Groovy code remains clean, efficient, and free from common pitfalls associated with variable usage.

How does Groovy support both static and dynamic typing?

Groovy supports both static and dynamic typing. By default, it's dynamically typed, but you can opt for static typing by explicitly declaring the data type or using the @CompileStatic annotation for stricter type checking.

What's the significance of Groovy's "safe navigation" feature?

The safe navigation operator ?. in Groovy allows you to avoid null pointer exceptions by returning a null value instead of throwing an error when trying to access a method or property on a null object.

Why choose Groovy over other JVM languages?

Groovy offers a blend of Java's robustness with added flexibility, making it ideal for tasks like scripting, testing, and building Domain-Specific Languages (DSLs). Its seamless integration with Java and the Grails web framework also makes it a popular choice for web development.

How does Groovy handle concurrency?

Groovy provides native support for concurrency through the GPars library, enabling developers to write parallel and asynchronous code more efficiently.

Let's see what you learned!

Which of the following statements about Groovy is TRUE?

Subscribe to our newsletter, subscribe to be notified of new content on marketsplash..

Public signup for this instance is disabled . Go to our Self serve sign up page to request an account.

Uploaded image for project: 'Groovy'

Multiple assignment

groovy multiple variable assignment

  • Status: Closed
  • Resolution: Fixed
  • Affects Version/s: None
  • Fix Version/s: 1.6-rc-2
  • Component/s: GEP
  • Labels: None

Description

Support for multiple assignment to simulate multiple return types:

a, b, c = someFunctionReturningAListOfThreeElements()

If more elements are returned than the number of variables to assign values to, we could get the head of list in the first variable and the rest of the list in the second variable:

head, tail = [1,2,3,4] assert head == 1 assert tail == [2,3,4]

Can also be used for variable swapping x, y = [y, x] x, y = y, x

We have to be careful with varibale definitions, because currently: def a, b, c = someFunctionReturningList() because currently, a and b would be null, while c would be assigned to the value of the return of the function.

A GEP should be created to present all the possibilities, syntax, edge cases.

Further ideas (subsequent feature enhancements) could be considered like fetching matching groups from regex: def regex = ~/firstname: (. ), name: (. )/ firstname, name = ("firstname: Guillaume, name: Laforge") =~ regex) assert firstname == "Guillaume" assert name == "Laforge"

Attachments

Issue links.

Task - A task that needs to be done.

  • Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to put multiple variables in groovy switch statement?

How to put multiple variables in groovy switch statement? eg. The if any variable is false, it will print "false" orelse print "true". The following script doesn't work

liuxu's user avatar

  • Doesn't this work for you? if (a && b && c) println "all true" else println "not all true" –  ulidtko Commented Aug 9, 2023 at 9:29

3 Answers 3

The switch statement is for testing a single value against multiple conditions.

While the switch statement is versatile , when testing multiple variables, a plain old if/else is more appropriate:

Alternatively you may use the in ( membership ) operator. It tests if the LHS operand (value) is contained in the RHS operand (collection).

zett42's user avatar

You could do something like the following, create a function that combines the three variables and switch on that. But I would not recommend it; the combination function is an unnecessary new element that could easily be buggy. You're better off using a series of if/else statements.

The above in Groovy Web Console

seansand's user avatar

You can use groovy.lang.Tuple :

One caveat here: bizarrely, Tuple extends java.util.AbstractList thus is an iterable "collection", AbstractList. And if you pass a collection in case label — groovy will try to do an "in list" element membership check . Meaning switch ("bar") { case ["foo", "bar", "buzz"]: ...} — will trigger.

For this reason, you need to wrap the concrete tuples in case-labels into a singleton list: case [new Tuple(true, true, true)] not case new Tuple(true, true, true) .

ulidtko's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged groovy or ask your own question .

  • Featured on Meta
  • Upcoming sign-up experiments related to tags
  • Policy: Generative AI (e.g., ChatGPT) is banned
  • The return of Staging Ground to Stack Overflow
  • The 2024 Developer Survey Is Live

Hot Network Questions

  • What's funny about "He leveraged his @#% deep into soy beans and cocoa futures" in The Jerk (1979)?
  • Looking at buying house with mechanical septic system. What questions should I be asking?
  • Why can't I connect a hose to this outdoor faucet?
  • Psychology Today Culture Fair IQ test question
  • Is there a way knowledge checks can be done without an Intelligence trait?
  • Hubble gyro manufacturrer
  • SetOptions does not work for ContourStyle of ContourPlot3D?
  • Did any Famicom game use microphone for random seed?
  • Academic Interview Question: "What is the title of your second book?"
  • How would I fix this leaking garage?
  • Is parapsychology a science?
  • Parts of Humans
  • How do I know how many enemies have I not found in the Hunter's Journal?
  • Would a series of gravitational waves from a supernova affect time on a 200 year old clock just as water waves affected clocks on ships in rough seas?
  • Can a creature with Mimicry activate command word magic items?
  • Binding to an IP address on an interface that comes and goes
  • How does this tensegrity table work?
  • Why is MSS important? Why can't we just rely on the MTU?
  • If humans colonized Earth 100,000 years ago, would we know it?
  • What distribution should I use to predict three possible outcomes
  • Scheme interpreter in C
  • What is the meaning of 多岁 in 在中国,60多岁已经是退休的年纪了?
  • Bringing a game console into Saudi Arabia
  • Maximum Power Transfer Theorem Question

groovy multiple variable assignment

COMMENTS

  1. Multiple assignments in groovy

    groovy multiple assignment with each closure fails. 1. Multiple assignment using a Map's value instead of a variable with Groovy ... Groovy: variable assignment. 1. Groovy: More elegant way to achieve this? 0. Assign class variables with a loop in groovy. Hot Network Questions A novel about people living hanging on the walls of huge building ...

  2. The Apache Groovy programming language

    Groovy supports multiple assignment, i.e. where multiple variables can be assigned at once, e.g.: def (a, b, c) = [10, 20, 'foo'] assert a == 10 && b == 20 && c == 'foo' ... Optional typing is the idea that a program can work even if you don't put an explicit type on a variable. Being a dynamic language, Groovy naturally implements that ...

  3. Multiple Variable Assignment in Groovy

    In one of my project, I was in need to return multiple variables from a method. I searched and found very good Groovy way for 'Multiple Assignment', This allows us to assign multiple variables at once. [groovy]def (str1,str2,str3) = ['Groovy','and','Grails']

  4. Groovy Goodness: Multiple Assignments

    Groovy Goodness: Multiple Assignments. Since Groovy 1.6 we can define and assign values to several variables at once. This is especially useful when a method returns multiple values and we want to assign them to separate variables. // Assign and declare variables.

  5. Semantics

    Groovy supports multiple assignment, i.e. where multiple variables can be assigned at once, e.g.: def (a, b, c) = [10, 20, 'foo'] assert a == 10 && b == 20 && c == 'foo' ... Optional typing is the idea that a program can work even if you don't put an explicit type on a variable. Being a dynamic language, Groovy naturally implements that ...

  6. Groovy Language Documentation

    Variable assignment. Multiple assignment; Overflow and Underflow; Object destructuring with multiple assignment; Control structures. Conditional structures. if / else; ... Groovy has always supported literal list/array definitions using square brackets and has avoided Java-style curly braces so as not to conflict with closure definitions. In ...

  7. Groovy Variable Scope

    3.3. Creating Global Variables from a Function Scope. We can also create global variables from inside a function scope. In this local scope, if we don't use any keyword in creating the variable, we'll create it in the global scope. Let's, then, create a global variable z in a new function: def defineGlobalVariable() {.

  8. Groovy: Basic Concepts: Variables, Storage and Commands

    Groovy supports a form of skip or command. Groovy supports the Java ';' line terminator as an optional element. A single ';' is interpreted as a skip. Assignments Groovy supports both single and multiple variable assignment. int a = 1 def b = c = 2 Sequential Commands Groovy supports sequential commands using the ';' as a separator.

  9. Groovy Goodness: Multiple Assignments Revisited

    Multiple assignments in Groovy is something already covered before in the Groovy Goodness series. But today at the Gr8Conf I got some extra information about it's possibilities. First of all we can use type information in the multiple assignment. So we can assign the returning values to typed variables.

  10. The Apache Groovy programming language

    This chapter covers Groovy Closures. A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. ... A closure can contain multiple statements: 1.2. Closures as an object. ... You can assign a closure to a variable, and it is an instance of groovy.lang.Closure: 2:

  11. Master Variables in Groovy with this Beginner Tutorial

    In Groovy, it is possible to assign multiple values to multiple variables in a single line. This feature is known as multiple assignments and can be useful in various scenarios. ... To explicitly assign a data type to a variable in Groovy, we can use the following syntax: def variable_name = value as Data_Type. For example, if we want to assign ...

  12. Using Multiple Assignments

    Using Multiple Assignments. Passing multiple arguments to methods is commonplace in many programming languages. Returning multiple results from functions, on the other hand, is not that common, though it can be quite convenient. We can return multiple results from functions and assign them to multiple variables in one shot.

  13. The Apache Groovy programming language

    Constructor usage, using coercion in assignment: 3.1.2. Named parameters. ... That means any method with an array as last parameter is seen by Groovy as a method that can take a variable number of arguments. ... Dynamic Groovy supports multiple dispatch (aka multimethods). When calling a method, the actual method invoked is determined ...

  14. Groovy

    Groovy supports all Java types (primitive and reference types). All primitives types are auto converted to their wrapper types. So int a = 2 will become Integer a = 2. When declaring variables we can do one of the followings: Do not use any type (that will create a global variable): a = 2. Use keyword def (that will create a local variable):

  15. Closures in Groovy

    A closure is an anonymous block of code. In Groovy, it is an instance of the Closure class. Closures can take 0 or more parameters and always return a value. Additionally, a closure may access surrounding variables outside its scope and use them — along with its local variables — during execution.

  16. Getting To Know Groovy Variables And Their Functions

    Learn about Groovy variables: types, scopes, and best practices. A concise guide for developers aiming to enhance their Groovy coding skills. ... After declaring a variable, you can assign a value to it. ... Groovy allows for the simultaneous declaration of multiple variables of the same type, making your code more concise. Variable Scope In ...

  17. [GROOVY-158] Multiple assignment

    If more elements are returned than the number of variables to assign values to, we could get the head of list in the first variable and the rest of the list in the second variable: head, tail = ... GROOVY-1543 Support multiple declarations at once: def a,b = 1,2. Closed; Activity. People. Assignee: Jochen Theodorou Reporter: James Strachan Votes:

  18. How to assign value to variable from a string split in groovy?

    You just need parenthesis instead of brackets: def str = "xyz=abc". def (name, value) = str.split("=") Note that you'll need to know how many elements you're expecting or you'll have unexpected results. answered Mar 28, 2012 at 20:36. Eric Wendelin. 43.9k 9 71 94.

  19. How to put multiple variables in groovy switch statement?

    You could do something like the following, create a function that combines the three variables and switch on that. But I would not recommend it; the combination function is an unnecessary new element that could easily be buggy. You're better off using a series of if/else statements. a = true b = true c = true switch(a.toString() + b.toString() + c.toString()) { case "truetruetrue": println ...