Home > database >  Splitting a string over multiple lines with no extra whitespaces using Groovy?
Splitting a string over multiple lines with no extra whitespaces using Groovy?

Time:08-20

Lets say I have a long string, and putting it on one line would decrease the readability.

This is would be the solution and it works:

def string = "This is a very\
long string"

But what if im in a Method or an if Statement were the lines are already indented. Then i would have to put the second part of the string like this which isnt very readable.

if (condition) {
    def string = "This is a very\
long string"
}

How can i make the output look like this:

This is a very long string

With something like this:

if (condition) {
    def string = "This is a very\
                  long string"
}

CodePudding user response:

If you would want to have the line breaks, there is stripMargin to help with removal of leading white space (at least until groovy supports the new multi-line string literals from Java).

But since you don't want the line breaks, I'd just "add" the strings. This usually is a no-no, because strings are immutable in java and this will create intermediate instances. Yet then the compiler should be able to optimize that, if you just add up string literals (the (dynamic) groovy compiler 4.x does not). But then again, it might not matter. And if you only want to pay once, make that a public static final String MY_CONST_STRING = ... somewhere.

if (1) { 
    println "This is a very "   
            "long string "   
            "and more" 
}

CodePudding user response:

How can i make the output look like this:

This is a very long string

The code you show in the question is an idiomatic way to do it if you really need/want the literal definition to span lines in the source file without including a newline character in the literal:

def string = "This is a very \
long string"

You could also do something like this:

def string = '\
this is a \
very long string.'
  • Related