Is there an operator that can crop a recess in a multi-line string?

This is really nice in Groovy:

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

Multiline strings. I saw in some languages ​​tools that take a step further and can remove the indentation of line 2 and so that the operator prints:

 First line, second line, last line 

but not

 First line, second line, last line 

Is this possible in Groovy?

+8
groovy
source share
1 answer

You can use stripMargin() for this:

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

If you do not need a leading character (for example, in the handset in this case), there is stripIndent() , but the line should be formatted a little differently (since minimal indentation is important)

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

from stripIndent

Separate leading spaces from each line in a line. The line with the least number of leading spaces defines the number to remove. Lines containing only spaces are ignored when calculating the number of leading spaces for the strip.


Update

Regarding the use of the operator for this, I personally do not recommend doing this. But for records, this can be done using Extension Mechanism or using categories (simpler and clunkier). An example of categories is as follows:

 class StringCategory { static String previous(String string) { // overloads `--` return string.stripIndent() } } use (StringCategory) { println(--''' hello world! from groovy multiline string ''') } 
+12
source share

All Articles