Introduction

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 comment
Multiline comment
JavaDoc comment
Shebang line

1.1.2. Keywords

1.1.3. Identifiers

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

def name
def item3
def with_underscore
def $dollarStart

But the following ones are invalid identifiers:

def 3tier
def a+b
def a#b
Quoted identifiers

1.1.4. Strings

Single quoted string
Double quoted string
Triple single quoted string
Triple double quoted string
Slashy string
Dollar slashy string

1.1.5. Numbers

Integer literal
Floating point literal
Binary literal
Octal literal
Hexadecimal literal
Underscore in literal
Number type suffixes

1.1.6. Booleans

1.1.7. Arrays

1.1.8. Lists

1.1.9. Maps

String keys
Parenthesized keys

1.2. Semantics

This chapter covers the semantic of the Groovy programming language.

1.2.1. Typing

Optional typing
Static type checking
Static compilation

1.2.2. Statements

Variable definition
Variable assignment
Multiple assignment
Control structures
Conditional structures
if / else
switch / case
Looping structures
Classic for loop
for in loop
while loop
Exception handling
try / catch / finally
Multi-catch
Power assertion
Labeled statements

1.2.3. Expressions

GPath expressions

1.2.4. Promotion and coercion

Number promotion
Closure to type coercion
Map to type coercion
String to enum coercion

1.2.5. Optionality

Optional parentheses
Optional semicolons
Optional return keyword
Optional public keyword

1.2.6. The Groovy Truth

Customizing the truth with asBoolean() methods

1.3. Operators

This chapter covers the operators of the Groovy programming language.

1.3.1. Arithmetic operators

1.3.2. Bitwise and logical operators

1.3.3. Conditional operators

Not operator
Ternary operator
Elvis operator

1.3.4. Object operators

Safe navigation operator
Direct field access operator
Method reference operator

1.3.5. Regular expression operators

Pattern operator
Find operator
Match operator

1.3.6. Other operators

Spread operator
Spreading method arguments
Spread list elements
Spread map elements
Range operator
Spaceship operator
Subscript operator
Membership operator
Identity operator
Coercion operator
Diamond operator
Call operator

1.3.7. Operator precedence

1.3.8. Operator overloading

1.4. Program structure

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

1.4.1. Package name

1.4.2. Imports

Default imports
Simple import
Star import
Static import
Static star import
Import aliasing

1.4.3. Scripts versus classes

1.4.4. Initializers

Static initializers
Instance initializers

1.5. Object orientation

This chapter covers the object orientation of the Groovy programming language.

1.5.1. Types

Primitive types
Class
Normal class
Static class
Inner class
Anonymous inner class
Abstract class
Interface
Annotation
Closure annotation parameters
Meta-annotations
Annotation placement
Constructors
Named argument constructor
Methods
Method definition
Named arguments
Default arguments
Varargs
Method selection algorithm
Exception declaration
Fields and properties
Fields
Properties
Inheritance
Generics

1.6. Closures

This chapter covers Groovy Closures.

1.6.1. Syntax

1.6.2. Parameters

Normal parameters
Implicit parameter
Default parameter
Varargs

1.6.3. Delegation strategy

1.6.4. Closures in GStrings

1.6.5. Functional programming

Currying
Left currying
Right currying
Index based currying
Memoization
Composition
Trampoline

2. Tools

2.1. groovyc, the Groovy compiler

2.1.1. Ant task

2.1.2. Maven integration

GMaven and GMavenPlus
The Groovy Eclipse Maven plugin

2.1.3. Command-line compiler

2.1.4. Joint compilation

2.2. groovysh, the Groovy shell

2.3. groovyConsole, the Groovy swing console

2.4. groovydoc, the Groovy & Java documentation generator

2.5. IDE integration

3. User Guides

3.1. Getting started

3.1.1. Download Groovy

3.1.2. Install Groovy

3.2. Differences with Java

3.2.1. Multi-methods

3.2.2. Array initializers

3.2.3. Package scope visibility

3.2.4. ARM blocks

3.2.5. Inner class instantiation

3.3. Groovy Development Kit

3.3.1. Working with IO

3.3.2. Working with collections

3.3.3. Handy utilities

ConfigSlurper
Expando
Observable list, map and set

3.4. Metaprogramming

3.4.1. Runtime metaprogramming

GroovyObject interface
invokeMethod
get/setProperty
get/setMetaClass
get/setAttribute
propertyMissing
methodMissing
GroovyInterceptable
Categories
Metaclasses
Custom metaclasses
Delegating metaclass
Magic package
Per instance metaclass
ExpandoMetaClass
Constructors
Borrowing methods
Dynamic method names
GroovyObject methods
Overriding static invokeMethod
Properties
Runtime discovery
Static methods
Extension modules
Module descriptor
Instance methods
Static methods

3.4.2. Compile-time metaprogramming

Developing AST transformations
Compilation phases guide
Local transformations
Global transformations
AST API guide
Testing AST transformations
Available AST transformations
Binding
@Bindable
@Vetoable
Constructors
@TupleConstructor
@InheritConstructors
@Singleton
@IndexedProperty
@ToString
@EqualsAndHashCode
@Canonical
@Immutable
@PackageScope
@Field
@ListenerList
Synchronization and locking
@Sinchronized
@WithReadLock
@WithWriterLock
Static typing and compilation
@TypeChecked
Custom type checking extensions
@CompileStatic
@CompileDynamic
Logging
@Log
@Commons
@Slf4j
@Log4j
@ASTTest
Metaprogramming
@Category
@Mixin
Execution control
@ThreadInterrupt
@TimedInterrupt
@ConditionalInterrupt
Other
@Grab
@GrabResolver
@GrabExclude
@Delegate
@Lazy
@Memoized
@AutoClone
@AutoExternalizable
@Newify

3.5. Testing guide

3.6. Interacting with a SQL database

3.7. Processing JSON

3.8. Processing XML

3.9. Scripting Ant tasks

3.10. Template engines

3.11. Servlet support

3.12. Integrating Groovy in a Java application

3.12.1. Groovy integration mechanisms

Eval
GroovyShell
GroovyClassLoader
CompilationUnit
Reloading

3.12.2. Bean Scripting Framework

3.12.3. JSR 223 javax.script API

3.13. Domain-Specific Languages

3.13.1. Command chains

3.13.2. Operator overloading

3.13.3. Script base classes

3.13.4. Adding properties to numbers

3.13.5. @DelegatesTo

3.13.6. Compilation customizers

Import customizer
AST customizer
Secure AST customizer
Source aware customizer
Customizer builder
Config script flag
AST transformations

3.13.7. Custom type checking extensions

3.13.8. Builders

Creating a builder
BuilderSupport
FactoryBuilderSupport
Existing builders
MarkupBuilder
StreamingMarkupBuilder
SaxBuilder
StaxBuilder
DomBuilder
NodeBuilder
JsonBuilder
StreamingJsonBuilder
SwingBuilder
AntBuilder
CliBuilder
ObjectGraphBuilder

3.14. Working with JMX

3.15. Creating Swing UIs

3.16. Security

3.17. Design patterns in Groovy