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.
- 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.
- 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.
- 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¶
Type | Literals | Notes |
---|---|---|
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 char | Represents a single Unicode character. Primitive type: char |
java.lang.Boolean | true , false | Primitive type: boolean |
java.lang.Byte | 0 as byte , -12 as byte | 8-bit integer. Primitive type: byte |
java.lang.Integer | 0 , -12 | 32-bit integer. Primitive type: int |
java.lang.Long | 0L , -12L | |
java.math.BigInteger | 0G , -12G | No upper limit on values. No primitive equivalent |
java.lang.Float | 0.0F , -12.12F | 32-bit, single-precision floating-point number. Primitive type: float |
java.lang.Double | 0.0D , -12.12D | 64-bit, double-precision floating-point number. Primitive type: double |
java.math.BigDecimal | 0.0 , -12.12 | Exact, 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 Set | Can 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.IntRange | 0..<10 , 1..100 | The 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 (').
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!
Operator | Method | Semantics |
---|---|---|
+ | 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 |
as | a.asType(b) | Type coercion |
a() | a.call() | Method call |
a[b] | a.getAt(b) | Array access |
a[b] = c | a.putAt(b, c) | Array mutation |
a in b | b.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 |
+a | a.positive() | Make positive |
-a | a.negative() | Make negative |
~a | a.bitwiseNegative() | Bitwise negate |
Other operators¶
These operators return true
or false
based on different types of comparison.
Comparators and other operators¶
Operator | Semantics |
---|---|
a b | Value-based equality |
a != b | Value-based inequality |
a < b | Less than |
a <= b | Less than or equal |
a > b | Greater than |
a >= b | Greater than or equal |
a <=> b | Compare (returns -1, 0, or 1 if a is less, equal or greater) |
a =~ b | Regex pattern match. Returns a Matcher , which equates to true if a matches any part of b . |
a ~ b | Regex pattern exact match. Returns true if a exactly matches b . |
a?.b | Null-safe navigation. Returns null if either a or b is null . |
a ? v1 : v2 | Ternary operator (concise if-else). Returns v1 if expression a evaluates to true , otherwise v2 . |
a ?: b | Elvis 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:
- Only the
if
is required and must come first. - You can have as many
else if
as you like. - 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
orfalse
according to Groovy Truth (see next sub section).
The only alternative is the switch
statement, which is like an extended if-else if-else
:
- Matches if this value is the same as the one in the
switch
. More generally, matches ifcaseValue.isCase(switchValue)
evaluates totrue
. break
is not required but without it, the followingcase
will always trigger too.- You can have as many
case
statements as you like. - 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¶
Type | Values equating to false | Values equating to true |
---|---|---|
String | Empty or null | Everything else |
Number | Zero or null | Everything else |
Collection | Empty or null | Everything else |
Map | Empty or null | Everything else |
Matcher (=~ ) | No match found | At 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
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
- 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.
- 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 catch
or 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 name Method name name
getName()
dateOfBirth
getDateOfBirth()
URLContent
getURLContent()
bookISBN
getBookISBN()