如何在 Groovy 多行字符串中使用字符串插值?

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

在 Groovy 中,我有一个用 ''' 定义的多行字符串,我需要在其中使用插值来替换其他一些变量。

尽管我尽了一切努力,但我无法让它发挥作用——我想我需要逃避一些我想念的东西。

下面是一些示例代码:

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

目前,输出:

${mexicanFood} & ${cretanFood}

虽然我很清楚:

Tacos & Dakos 

(注意 - 我不想连接字符串)

不要对 GStringmulti-line string 使用 ''',而是使用 """

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

GString 包含在 ''' 中将无法解析 placeholder - $。您可以在标题 StringString Summary Table 块下的 Groovy Documentation 中找到更多详细信息。

在 Groovy 中,单引号用于创建不可变字符串,就像 Java 使用双引号一样。

当您在 Groovy 中使用双引号时,您向运行时表明您打算创建一个可变字符串或 Groovy 字符串(简称 GString)。您可以对可变字符串使用变量插值,或者您可以将其保留为普通的 Java String.

此行为扩展到多行字符串版本;三重单引号的使用创建了一个不可变的多行字符串,而三重双引号创建了一个 Groovy 字符串。

从三重引号中添加变量并将它们与内容连接起来也可能是个好主意。 对于引号内包含复杂内容的情况,类似这样的情况:

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

既然你的情况很简单,这应该也能做到:

def bestRestaurant = mexicanFood + " & " + cretanFood