yegor256 yegor256 - 1 year ago 122
Groovy Question

What's wrong with Groovy multi-line String?

Groovy scripts raises an error:

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


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"


Answer Source

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" +

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

Will create a String with test on three lines

Also, you can make it neater by:

def a = """test

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