11

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?

Binders Lachel
  • 505
  • 1
  • 5
  • 14

1 Answers1

17

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
           ''') 
}
kdabir
  • 9,623
  • 3
  • 43
  • 45
  • really nice! Does this work only on GStrings? Would it be possible to somehow "overload" an operator to make this method call transparent? – Binders Lachel Mar 09 '14 at 12:29
  • It works on Strings as well. Regarding ovarloading an operator, it should be possible with extension methods or Categories. Updating the answer. – kdabir Mar 09 '14 at 13:48
  • excellent! and is it possible to set the StringCategory to be default, or available everywhere? – Binders Lachel Mar 09 '14 at 16:19
  • 1
    For that, you need to use Extension Mechanism. See details here: http://mrhaki.blogspot.in/2013/01/groovy-goodness-adding-extra-methods.html – kdabir Mar 09 '14 at 17:44