Skip to content
Philip Ford edited this page Jan 15, 2017 · 30 revisions

Enough Groovy to be dangerous

Basics

  • Very similar to Java, but less verbose.
  • Files have .groovy extensions
  • Semicolons are optional at the end of lines.

Default Imports

The following packages are automatically imported by Groovy, so you don't have to import them:

import java.lang.*
import java.util.*
import java.io.*
import java.net.*
import groovy.lang.*
import groovy.util.*
import java.math.BigInteger
import java.math.BigDecimal

The def keyword

It means that datatype or return type of a property/function/method is unspecified, and that Groovy will attempt to infer the type.

  • It does declare a standalone function per se. It is a return type.
  • If you use a visibility modifier, the presence of def is unnecessary.

Functions

  • Can be invoked without parentheses around the parameter list.

Operators

The Elvis Operator

A more concise ternary operator: ?:

def sampleText
 
// Normal ternary operator.
def ternaryOutput = (sampleText != null) ? sampleText : 'Hello Groovy!'
 
// The Elvis operator in action. We must read: 'If sampleText is not null assign
// sampleText to elvisOuput, otherwise assign 'Viva Las Vegas!' to elvisOutput.
def elvisOutput = sampleText ?: 'Viva Las Vegas!'

Visibility

  • Everything has public visibility by default.
    • This means that if you omit the visibility modifier for a class/method, the visibility is public.
  • To assign package (default) visibility to a class or method, you must annotate it with @PackageScope.

Clone this wiki locally