What's wrong with Groovy multi-line String?

StringGroovyMultiline

String Problem Overview


Groovy scripts raises an error:

def a = "test"
  + "test"
  + "test"

Error:

No signature of method: java.lang.String.positive() is 
applicable for argument types: () values: []

While this script works fine:

def a = new String(
  "test"
  + "test"
  + "test"
)

Why?

String Solutions


Solution 1 - String

As groovy doesn't have EOL marker (such as ;) it gets confused if you put the operator on the following line

This would work instead:

def a = "test" +
  "test" +
  "test"

as the Groovy parser knows to expect something on the following line

Groovy sees your original def as three separate statements. The first assigns test to a, the second two try to make "test" positive (and this is where it fails)

With the new String constructor method, the Groovy parser is still in the constructor (as the brace hasn't yet closed), so it can logically join the three lines together into a single statement

For true multi-line Strings, you can also use the triple quote:

def a = """test
test
test"""

Will create a String with test on three lines

Also, you can make it neater by:

def a = """test
          |test
          |test""".stripMargin()

the stripMargin method will trim the left (up to and including the | char) from each line

Solution 2 - String

Similar to stripMargin(), you could also use stripIndent() like

def a = """\
        test
        test
        test""".stripIndent()

Because of

> The line with the least number of leading spaces determines the number to remove.

you need to also indent the first "test" and not put it directly after the inital """ (the \ ensures the multi-line string does not start with a newline).

Solution 3 - String

You can tell Groovy that the statement should evaluate past the line ending by adding a pair of parentheses ( ... )

def a = ("test"
  + "test"
  + "test")

A second option is to use a backslash, \, at the end of each line:

def a = "test" \
  + "test" \
  + "test"

FWIW, this is identical to how Python multi-line statements work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionyegor256View Question on Stackoverflow
Solution 1 - Stringtim_yatesView Answer on Stackoverflow
Solution 2 - StringsschuberthView Answer on Stackoverflow
Solution 3 - StringcmcgintyView Answer on Stackoverflow