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

gsaslis picture gsaslis · Sep 27, 2016 · Viewed 31.9k times · Source

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)

Answer

Abhinandan Satpute picture Abhinandan Satpute · Sep 27, 2016

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.