Using Substitution Expressions in Strings

Groovy supports using two kinds of string literals, normal strings and strings with substitution expressions. To define a normal string literal, use single quotes to surround the contents like this:

// These are normal strings
def name = 'Steve'
def confirmation = '2 message(s) sent to ' + name

To define a string with substitution expressions, use double-quotes to surround the contents. The string value can contain any number of embedded expressions using the ${ expression } syntax. For example, you could write:

// The confirmation variable is a string with substitution expressions
def name = 'Steve'
def numMessages = 2
def confirmation = "${numMessages} message(s) sent to ${name}"

Executing the code above will end up assigning the value 2 messages(s) sent to Steve to the variable named confirmation. It does no harm to use double-quotes all the time, however if your string literal contains no substitution expressions it is slightly more efficient to use the normal string with single-quotes.

Tip: As a rule of thumb, use normal (single-quoted) strings as your default kind of string, unless you require the substitution expressions in the string.