04.07.2013 Views

Programming Grails - Cdn.oreilly.com

Programming Grails - Cdn.oreilly.com

Programming Grails - Cdn.oreilly.com

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Using a StringBuilder (the preferred approach when concatenating in a loop) wouldn’t<br />

be much better in this case. But using a GString (along with property syntax), we can<br />

join the data in a single line of code:<br />

def fullName = "$person.firstName ${person.initial ? person.initial + ' '<br />

: ''}$person.lastName"<br />

GStrings also work with multiline strings as long as you use three double quotes; this<br />

is convenient for tasks such as filling in templates for emails:<br />

def template = """\<br />

Dear $name,<br />

Thanks for signing up for the Ralph's Bait and Tackle online store!<br />

We appreciate your business and look forward to blah blah blah …<br />

Ralph<br />

"""<br />

Here, I’m using the backslash character at the beginning of the string to avoid having<br />

an initial blank line. You can use three single quotes to create multiline strings, but they<br />

behave like regular strings that use single quotes, in that they do not support expression<br />

replacement.<br />

Using the subscript operator lets you conveniently access substrings:<br />

String str = 'Groovy Strings are groovy'<br />

assert str[4] == 'v' // a String of length 1, not a char<br />

assert str[0..5] == 'Groovy' // the first 6 chars<br />

assert str[19..-1] == 'groovy' // the last 6 chars<br />

assert str[15..17] == 'are' // a substring in the middle<br />

assert str[17..15] == 'era' // a substring in the middle, reversed<br />

Static this<br />

Unlike Java where the this keyword only makes sense in instance scope, this resolves<br />

to the class in static scope. One use of this feature is when defining static loggers. In<br />

Log4j and SLF4J, you can define a logger with a class or the class name (or any string<br />

you like), but in Java, there’s no way (no convenient one anyway) to get the class name<br />

in static scope. This can lead to copy/paste problems. For example:<br />

private static final Logger LOG = Logger.getLogger(Foo.class);<br />

has the class hardcoded, so if you forget to change it and copy that to a different class,<br />

you’ll be logging as the wrong category. Instead, in Groovy, you can use:<br />

private static final Logger LOG = Logger.getLogger(this)<br />

which is more portable (and similar to the analogous instance version private final<br />

Logger log = Logger.getLogger(getClass())).<br />

20 | Chapter 1: Introduction to Groovy

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!