Question

This is really nice in Groovy:

println '''First line,
           second line,
           last line'''

Multi-line strings. I have seen in some languages tools that take a step further and can remove the indentation of line 2 and so, so that statement would print:

First line,
second line,
last line

and not

First line,
           second line,
           last line

Is it possible in Groovy?

Était-ce utile?

La solution

You can use stripMargin() for this:

println """hello world!
        |from groovy 
        |multiline string
    """.stripMargin()

If you don't want leading character (like pipe in this case), there is stripIndent() as well, but string will need to be formatted little differently (as minimum indent is important)

println """
        hello world!
        from groovy 
        multiline string
    """.stripIndent()

from docs of stripIndent

Strip leading spaces from every line in a String. The line with the least number of leading spaces determines the number to remove. Lines only containing whitespace are ignored when calculating the number of leading spaces to strip.


Update:

Regarding using a operator for doing it, I, personally, would not recommend doing so. But for records, it can be done by using Extension Mechanism or using Categories (simpler and clunkier). Categories example is as follows:

class StringCategory {
    static String previous(String string) { // overloads `--`
        return string.stripIndent()
     }
}

use (StringCategory) {
    println(--'''
               hello world!
               from groovy 
               multiline string
           ''') 
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top