How do I use String interpolation in a Groovy multiline string?

GroovyString Interpolation

Groovy Problem Overview


In Groovy, I have a multiline String, defined with ''', in which I need to use interpolation in order to substitute some other variables.

For all my efforts, I can't get it to work -- I assume I need to escape something, which I'm missing.

Here's some sample code:

def cretanFood = "Dakos" 
def mexicanFood = "Tacos"
def bestRestaurant = ''' 
${mexicanFood} & ${cretanFood}
'''
print bestRestaurant

At the moment, this outputs:

${mexicanFood} & ${cretanFood}

while I would clearly expect:

Tacos & Dakos 

(Note - I would prefer not to concatenate the strings)

Groovy Solutions


Solution 1 - Groovy

Instead of using ''' for the GString or multi-line string use """

def cretanFood     = "Dakos"  
def mexicanFood    = "Tacos"
def bestRestaurant = """${mexicanFood} & ${cretanFood}"""
print bestRestaurant​

GString enclosed in ''' will not be able to resolve the placeholder - $. You can find more details in the Groovy Documentation under the heading String and String Summary Table block.

Solution 2 - Groovy

In Groovy, single quotes are used to create immutable Strings, just exactly like Java does with double quotes.

When you use double quotes in Groovy you indicate to the runtime your intention to create a mutable String or Groovy String (GString for short). You may use variable interpolation with mutable Strings, or you can leave it as a regular plain Java String.

This behavior extends to the multi-line String versions; usage of triple single quotes creates an immutable multi-line String whereas triple double quotes creates a Groovy String.

Solution 3 - Groovy

It may also be a good idea to add the variables out of the triple quotes and just concatenate them with the content. Something like this for the cases you have complex content inside the quotes:

def bestRestaurant = mexicanFood + """ & """ + cretanFood

Since your case is quite simple, this should do it as well:

def bestRestaurant = mexicanFood + " & " + cretanFood

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiongsaslisView Question on Stackoverflow
Solution 1 - GroovyAbhinandan SatputeView Answer on Stackoverflow
Solution 2 - GroovyAndres AlmirayView Answer on Stackoverflow
Solution 3 - GroovySasho AndrijeskiView Answer on Stackoverflow