Groovy Cheat Sheet

  



Is there a groovy cheat sheet available anywhere? I didn't see anything obvious in the documentation, but of course, there's an impressive amount of documentation to look through:-) Also, is there a standard Groovy wiki site I could perhaps create such a cheat sheet, if it is needed? Here you can find documentation on all of Groovy's commands and features. Add to Discord Commands Premium Support Login 🍪 Hey! Do you like cookies? We do, so we implemented some in our website! Add to Discord Commands Premium Support Login Commands All Basic Player Queue Audio Effects.

Welcome to the Groovy cheat sheet!

This is a condensed reference for Groovy syntax and other information that you might regularly want to look up.

  1. Groovy; Groovy Cheatsheet. Created by Jana Volencova. This section is meant as a quick library of copy/paste code snippets. For details on functions, refer to the API Documentation. Calculated Field Set. Get the current processed item (e.g.
  2. Java, Groovy cheat sheet. Idiom ID Imports Comments Links Only entries having Java Only entries having Groovy The snippets are under the CC-BY-SA license. Consider printing in landscape mode; or not printing at all, and keeping a bookmark.
  3. A multi-faceted language for the Java platform. Apache Groovy is a powerful, optionally typed and dynamic language, with static-typing and static compilation capabilities, for the Java platform aimed at improving developer productivity thanks to a concise, familiar and easy to learn syntax.It integrates smoothly with any Java program, and immediately delivers to your application powerful.

Core types and operators¶

Groovy comes with a selection of the basic types you'd expect, such as strings and numbers. Most of them are part of the standard Java class library, although Groovy introduces some new literals.

Type list¶

TypeLiteralsNotes
java.lang.String'hi', 'hi', /hi/, $/hi/$Double quotes allow embedded expressions. Slashes mean you don't need to escape characters, the dollar slashes mean you don't need to escape / characters (good for regular expressions).
java.lang.Character'H' as charRepresents a single Unicode character. Primitive type: char
java.lang.Booleantrue, falsePrimitive type: boolean
java.lang.Byte0 as byte, -12 as byte8-bit integer. Primitive type: byte
java.lang.Integer0, -1232-bit integer. Primitive type: int
java.lang.Long0L, -12L
java.math.BigInteger0G, -12GNo upper limit on values. No primitive equivalent
java.lang.Float0.0F, -12.12F32-bit, single-precision floating-point number. Primitive type: float
java.lang.Double0.0D, -12.12D64-bit, double-precision floating-point number. Primitive type: double
java.math.BigDecimal0.0, -12.12Exact, uncapped floating-point number. No, primitive equivalent.
java.util.List[], [1, 2, 3]Can contain values of any type.
java.util.Set[] as Set, [1, 2, 3] as SetCan contain values of any type.
java.util.Map[:], [one: 1, two: 2]String keys don't need quotes when using the map literal.
groovy.lang.IntRange0..<10, 1..100The first literal excludes the upper bound, whereas the second includes it. The lower bound is always included.

In addition to all the string literal variants shown in the table above, you can create multi-line strings by using three quotes in a rows. For example:

You can use single or double quotes, with the latter allowing you to embed Groovy expressions (the behavior matches that of the equivalent normal strings).

Line continuations allow you to split long lines of text across multiple lines of your source code:

For this to work, you can't have any characters, even whitespace, after the backslash (').

Cheat

Coercions¶

Groovy allow you to easily convert values from one type to another if the conversion is known, for example String -> Character, or List -> Set. Either declare a variable of the target type:

or use the as operator:

The as operator is more flexible as it can be used for method arguments too:

Without the coercion, the above code would throw a MissingMethodException.

Overloadable operators¶

Groovy allows you to implement operators in your own classes by implementing methods with specific signatures. You can also use the method names to look up what operators are supported by types in the Java class library and Groovy JDK extensions.

Here's a list of such operators and what they generally mean. Try not to deviate from the semantics when you do your own operator overloading!

OperatorMethodSemantics
+a.plus(b)Addition
-a.minus(b)Subtraction
*a.multiply(b)Multiplication
/a.div(b)Division
%a.mod(b)Modulo/remainder
**a.power(b)Exponentiation
|a.or(b)Bitwise OR
&a.and(b)Bitwise AND
^a.xor(b)Bitwise XOR
asa.asType(b)Type coercion
a()a.call()Method call
a[b]a.getAt(b)Array access
a[b] = ca.putAt(b, c)Array mutation
a in bb.isCase(a)'is one of'
<<a.leftShift(b)Left shift or append
>>a.rightShift(b)Right shift
>>>a.rightShiftUnsigned(b)Unsigned right shift
++a.next()Increment value
--a.previous()Decrement value
+aa.positive()Make positive
-aa.negative()Make negative
~aa.bitwiseNegative()Bitwise negate

Other operators¶

These operators return true or false based on different types of comparison.

Comparators and other operators¶

OperatorSemantics
a bValue-based equality
a != bValue-based inequality
a < bLess than
a <= bLess than or equal
a > bGreater than
a >= bGreater than or equal
a <=> bCompare (returns -1, 0, or 1 if a is less, equal or greater)
a =~ bRegex pattern match. Returns a Matcher, which equates to true if a matches any part of b.
a ~ bRegex pattern exact match. Returns true if aexactly matches b.
a?.bNull-safe navigation. Returns null if either a or b is null.
a ? v1 : v2Ternary operator (concise if-else). Returns v1 if expression a evaluates to true, otherwise v2.
a ?: bElvis operator. Returns value of a if it equates to true (Groovy Truth), otherwise returns b.

Flow control¶

This section covers conditions, loops, and error handling via exceptions.

Conditions¶

Groovy Cheat Sheet

The most common conditional in Groovy is the if statement:

  1. Only the if is required and must come first.
  2. You can have as many else if as you like.
  3. You can only have a single else and it must come last.

Other notes:

  • The curly braces are optional if the body of the block is only a single statement.
  • must resolve to true or false according to Groovy Truth (see next sub section).

The only alternative is the switch statement, which is like an extended if-else if-else:

  1. Matches if this value is the same as the one in the switch. More generally, matches if caseValue.isCase(switchValue) evaluates to true.
  2. break is not required but without it, the following case will always trigger too.
  3. You can have as many case statements as you like.
  4. If none of the case statements match, this will trigger. It is not required.

Groovy Truth¶

Groovy will automatically coerce expressions to boolean values where a boolean is required, for example in an if statement. Here are some standard coercions:

Groovy Truth coercions¶

TypeValues equating to falseValues equating to true
StringEmpty or nullEverything else
NumberZero or nullEverything else
CollectionEmpty or nullEverything else
MapEmpty or nullEverything else
Matcher (=~)No match foundAt least one match

Loops¶

Groovy has two main loops: for and while. There is no do-while. The predominant syntax for the for loop is:

where is a typed or untyped variable and is something that can be iterated over, such as a list or a range of numbers. For example, iterating over numbers can be done with:

Here's an example of iterating over a list of strings:

Note

The above form of for works for any instance of java.lang.Iterable, such as collections and strings.

There is a less common form of the for loop which mimics the behaviour of Java:

This is rarely used and should be avoided if possible. It doesn't support the , operator that allows initialisation of multiple variables, so it's not completely consistent with Java. That makes is confusing for people coming from that language.

The while loop is straightforward:

where <expr> is an expression that can be evaluated to a boolean according to Groovy Truth.

For completeness, another common approach to iteration is with the each() method:

One notable disadvantage of this approach is that Groovy can't infer the type of the objects in the iterable, so it's often best to explicitly declare the type of the closure argument. See later for more closure syntax.

Exceptions¶

The normal mechanism for error handling in Groovy is via exceptions, same as for Java. Unlike Java, though, Groovy treats all exceptions as runtime ones, which means the compiler does not force you to catch them.

Here is the basic syntax:

Groovy Read Excel

  1. Catch expressions are evaluated in declared order, so the first one that matches the thrown exception wins. Hence you normally order them from most specific to least specific.
  2. The finally block always executes, regardless of whether the code throws an exception or not.

Note

The try is required, but the catch and finally blocks are optional. You have to have at least one catchor a finally, though.

Groovy Cheat Sheet Template

Throwing an exception is even easier:

In other words, you instantiate an exception just like any other object and use it as the argument to throw. You can also use throw to rethrow an exception from a catch block. And just as you can pass arguments when creating normal objects, you can do the same with exceptions. One of the most common arguments (supported by most exceptions) is a message explaining the error:

If you want to execute the same block of code for more than one different exception, you can use a multi-catch block:

So in general, a catch takes the form:

where * indicates 0 or more of what's in the square brackets.

Classes¶

Important

Hubitat runs custom apps and drivers in a script sandbox and does not support creating your own groovy classes

Objects¶

Jenkins Groovy Script Examples

Objects are instances of classes. To create new objects, you can either use literals, such as those described in the <

The GroovyBeans constructor syntax still works, though. Here are some examples of how property names maps to methods:

Property naming convention¶

Property nameMethod name
namegetName()
dateOfBirthgetDateOfBirth()
URLContentgetURLContent()
bookISBNgetBookISBN()