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?
Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.
Use textwrap.Call textwrap. dedent(s) to remove indentation from s .
Groovy is indentation-unaware, but it's good engineering practice to follow the usual indentation schemes for blocks of code. Groovy is mostly unaware of excessive whitespace, with the exception of line breaks that end the current statement and single-line comments.
You can indent the lines in a string by just padding each one with proper number of pad characters. This can easily be done by using the textwrap. indent() function which was added to the module in Python 3.3.
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
''')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With