Search code examples
groovy

Groovy multi-line string stripIndent() with interpolated string from `join("\n")` array


When I use the results of a .join("\n") array in a multi-line string then stripIndent() doesn't appear to work:

def list = [ 'one', 'two' ]
def listAsString = list.join("\n")

def string = """\
  First line for listAsString

  $listAsString

  Last line
""".stripIndent()

Note: I am using the escaped first line.

This produces:

  First line for listAsString

  one
two

  Last line

Instead of

First line for listAsString

one
two

Last line

However if I use it with a normal variable it works OK:

def exampleVar = 'fred'

def string2 = """\
  First line for plain list
  
  $exampleVar

  Last line
""".stripIndent()

Produces:

First line for plain list

fred

Last line

This is as I would expect.

Is there something special I need to do if join()ing an array for use in a multi-line string?


Solution

  • Straight from the javadoc:

    Strips leading spaces from every line in a CharSequence. 
    The line with the least number of leading spaces determines the number to remove.
    

    So your join should insert also 2 or whatever number spaces to match the minimal ident:

    def list = [ 'one', 'two' ]
    def listAsString = list.join "\n  "
        
    def string = """\
      First line for listAsString
    
      $listAsString
    
      Last line
    """.stripIndent()
    
    assert string == '''\
    First line for listAsString
    
    one
    two
    
    Last line
    '''