Search code examples
groovystring-interpolation

String interpolation in a multi-line Groovy string


I have a multi-line string in which I dynamically populate an SQL query from a map. I am getting a MissingPropertyException that is a result of the query not recognising the map key or values. Is there a way around this?

def multiString = """
def person = ['John': 'Builder']

person.each{ key, value ->

String query = """ UPDATE person SET value = '${value}' 
                   WHERE name = '${key}' """ } 
 """

Solution

  • I figured it out. I needed to escape the $ using a backslash.

    def multiString = """
      def person = ['John': 'Builder']
    
      person.each{ key, value ->
    
      String query = """ UPDATE person SET value = '\${value}'
                         WHERE name = '\${value}' """ } 
    """