Working with Numbers, Dates, and Strings
Groovy makes it easy to work with numbers, dates and strings. The expression for a literal number is just the number itself:
// Default discount is 5%
def defaultDiscount = 0.05
// Assume 31 days in a month
def daysInMonth = 31
To create a literal date, use the
date()
or dateTime()
function:// Start by considering January 31st, 2019
def lastDayOfJan = date(2019,1,31)
// Tax forms are late after 15-APR-2019 23:59:59
def taxSubmissionDeadline = dateTime(2019,4,15,23,59,59)
Write a literal string using a matching pair of single quotes, as shown here.
// Direct users to the Acme support twitter account
def supportTwitterHandle = '@acmesupport'
It is fine if the string value contains double-quotes, as
in:
// Default podcast signoff
def salutation = 'As we always say, "Animate from the heart."'
However, if your string value contains single quotes, then use a matching pair of
double-quotes to surround the value like
this:
// Find only gold customers with credit score over 750
customers.appendViewCriteria("status = 'Gold' and creditScore > 750")
You can use the normal +
and -
operators to do date,
number, and string arithmetic like this:
// Assign a date three days after the CreatedDate
def targetDate = CreatedDate + 3
// Assign a date one week (seven days) before the value
// of the SubmittedDate field
def earliestAcceptedDate = SubmittedDate - 7
// Increase an employee's Salary field value by 100 dollars
Salary = Salary + 100
// Decrement an salesman's commission field value by 100 dollars
Commission = Commission - 100
// Subtract (i.e. remove) any "@"-sign that might be present
// in the contact's twitter name
def twitNameWithoutAtSign = ContactTwitterName - '@'
// Add the value of the twitter name to the message
def message = 'Follow this user on Twitter at @' + twitNameWithoutAtSign