Using Conditional Expressions
When you need to perform the conditional logic, you use the familiar if/else construct.
For example, in the text fragment example in the previous section, if the current object's
ContactTwitterName
returns null
, then you won't want to
include the static text related to a twitter name. You can accomplish this conditional text
inclusion using if
/else
like this:
def textFragment = 'We will try to call you at ' + ContactPhoneNumber
if (ContactTwitterName != null) {
textFragment += ', or send you a tweet at '+ContactTwitterName
}
else {
textFragment += '. Give us your twitter name to get a tweet'
}
textFragment += '.'
While sometimes the traditional if
/else
block is more easy
to read, in other cases it can be quite verbose. Consider an example where you want to define
an emailToUse
variable whose value depends on whether the
EmailAddress
field ends with a .gov
suffix. If the primary
email ends with .gov
, then you want to use the
AlternateEmailAddress
instead. Using the traditional
if
/else
block your script would look like this:
// Define emailToUse variable whose value is conditionally
// assigned. If the primary email address contains a '.gov'
// domain, then use the alternate email, otherwise use the
// primary email.
def emailToUse
if (endsWith(EmailAddress,'.gov') {
emailToUse = AlternateEmailAddress
}
else {
emailToUse = EmailAddress
}
Using Groovy's handy inline if
/ then
/
else
operator, you can write the same code in a lot fewer lines:
def emailToUse = endsWith(EmailAddress,'.gov') ? AlternateEmailAddress : EmailAddress
The inline if
/ then
/ else
operator has
the following general syntax:
BooleanExpression
?
If_True_Use_This_Expression
:
If_False_Use_This_Expression
Since you can use whitespace to format your code to make it more readable, consider wrapping inline conditional expressions like this:
def emailToUse = endsWith(EmailAddress,'.gov')
? AlternateEmailAddress
: EmailAddress