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

笑着哭i 提交于 2020-03-18 03:09:12

问题


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)


回答1:


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.




回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/39721112/how-do-i-use-string-interpolation-in-a-groovy-multiline-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!