Strings and GStrings

Groovy has one string type and five ways to write it. The quotes decide whether the text is interpolated, and a double-quoted string is not a String at all: it is a GString, a template that becomes a string when something needs one.

Five forms

forms.groovy

def name = 'Ada' println 'single: no interpolation, ${name} stays' println "double: interpolation, ${name} and $name" println '''triple single: ${name} stays, and a newline is allowed''' println '''triple double: ${name}, and a newline is allowed''' println(/slashy: ${name} stays/) println($/dollar slashy: ${name} works, and $$ is one dollar/$)

groovy forms.groovy

single: no interpolation, ${name} stays
double: interpolation, Ada and Ada
triple single: ${name} stays,
and a newline is allowed
triple double: ${name},
and a newline is allowed
slashy: Ada stays
dollar slashy: Ada works, and $ is one dollar

A slashy string is a regex written as a string: a pattern needs one backslash, not the two a Java string literal needs, and \/ is a literal slash. A dollar-slashy string is the same with $/ as its delimiters, $$ as a literal dollar and no escaping of a quote.

A GString is not a String

The class behind the interpolation matters in two places: equality against a String works, because Groovy compares the text, but a map key does not, because the hash code comes from the template:

gstring.groovy

def name = 'Ada' def key = "${name}" println key.getClass().name println(key == 'Ada') def ages = [(key): 36] println ages['Ada'] println ages[key]

groovy gstring.groovy

org.codehaus.groovy.runtime.GStringImpl
true
null
null

The lookup with a plain string finds nothing, because the key in the map is the GString. The fix is key.toString(), or single quotes when nothing needs interpolating. The language keeps the trap on purpose: a GString carries its parts, so building one and converting it are different acts.

Expressions inside the braces

${...} holds any expression, and $name is the short form for a property, a variable or a field. A method call needs the braces:

expressions.groovy

def items = ['pen', 'book'] println "first: ${items[0]}" println "count: ${items.size()}" println "upper: ${items[1].toUpperCase()}" println "sum: ${2 + 3}" println "format: ${String.format('%03d', 7)}"

groovy expressions.groovy

first: pen
count: 2
upper: BOOK
sum: 5
format: 007

A single-quoted string is cheaper, because it is an ordinary java.lang.String and no template object is built. A message with no interpolation belongs in single quotes, which is also what CodeNarc asks for.

Related

Автор статьи: Arthur Isaev