Strings and GStrings
Prerequisites: Data types
Groovy has several ways to write text. The two you'll use most:
single quotes for plain strings and double quotes for
GStrings — strings with ${} placeholders.
def name = 'Ada'
def age = 36
def book = [title: 'Dune']
println 'Hello, $name' // single quotes: no interpolation
println "Hello, $name" // $variable
println "Next year: ${age + 1}" // ${expression}
println "Upper: ${name.toUpperCase()}"
println "Book: $book.title" // $a.b works for properties
println "Price: \$5" // escape a literal dollar
Hello, $name
Hello, Ada
Next year: 37
Upper: ADA
Book: Dune
Price: $5
$nameinserts a variable;${ ... }inserts any expression.$book.titlereads the propertytitle— but$name.size()would not call the method; use${name.size()}for method calls.- Single-quoted strings are plain
java.lang.Strings.
Multi-line strings
def user = 'ada'
def email = """\
Hi $user,
Your report is ready.
— The Team""".stripIndent()
println email
def sql = '''
SELECT *
FROM users
'''.trim()
println sql
Hi ada,
Your report is ready.
— The Team
SELECT *
FROM users
Triple quotes (''' plain, """ with placeholders) span lines. The
backslash after the opening quotes skips the first new line, and
stripIndent() removes the common leading spaces.
Slashy strings
def path = /C:\Users\ada\notes.txt/
println path
def pattern = /\d{3}-\d{4}/
println '555-1234' ==~ pattern
C:\Users\ada\notes.txt
true
Between slashes, backslashes are literal — ideal for regular
expressions and Windows paths. (==~ tests a regex match; Level 2
covers regexes.)
Concatenation and repetition
println 'Groovy' + ' ' + 'rocks'
println '-' * 20
println 'abc' + 1 + 2
println 1 + 2 + 'abc'
Groovy rocks
--------------------
abc12
3abc
+ joins strings, * repeats them. Evaluation goes left to right, so
1 + 2 + 'abc' adds the numbers first.
GString gotcha
def key = "id"
def gkey = "${key}"
println 'id' == gkey
println gkey.class.simpleName
def map = [(gkey.toString()): 1]
println map['id']
true
GStringImpl
1
A GString compares equal to a String with ==, but it's a different
class with a different hash code — so don't use GStrings as map
keys. Call toString() first, or use single-quoted strings.