Multiline strings are very useful in Groovy. But sometimes they can mess up our code formatting especially if we want to use the multiline string's value literally. If our lines cannot start with spaces we must define our multiline string that way:
class Simple { String multi() { '''\ Multiline string with simple 2 space indentation.''' } // Now in Groovy 1.7.3: String multi173() { '''\ Multiline string with simple 2 space indentation.'''.stripIndent() } }
Since Groovy 1.7.3 we can strip leading spaces from such lines, so we can align the definition of our multiline string the way we want with the stripIndent()
method. Groovy finds the line with the least spaces to determine how many spaces must be removed from the beginning of the line. Or we can tell the stripIndent()
method how many characters must be removed from the beginning of the line.
def multi = '''\ Multiline string with simple 2 space indentation.''' assert '''\ Multiline string with simple 2 space indentation.''' == multi.stripIndent() assert '''\ ine string imple 2 space ation.''' == multi.stripIndent(8) // We can define the number of characters ourselves as well.