Groovy多行字符串出了什么问题?

yeg*_*256 93 string groovy multiline

Groovy脚本引发错误:

def a = "test"
  + "test"
  + "test"
Run Code Online (Sandbox Code Playgroud)

错误:

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

虽然这个脚本工作正常:

def a = new String(
  "test"
  + "test"
  + "test"
)
Run Code Online (Sandbox Code Playgroud)

为什么?

tim*_*tes 212

由于groovy没有EOL标记(例如;),如果将操作符放在下一行,它会变得混乱

这将改为:

def a = "test" +
  "test" +
  "test"
Run Code Online (Sandbox Code Playgroud)

因为Groovy解析器知道在下一行上有所期待

Groovy将您的原始内容def视为三个单独的语句.第一个分配testa,第二个尝试做出"test"正面(这是它失败的地方)

使用new String构造函数方法,Groovy解析器仍然在构造函数中(因为大括号尚未关闭),因此它可以在逻辑上将三行连接成一个语句

对于真正的多行字符串,您还可以使用三重引号:

def a = """test
test
test"""
Run Code Online (Sandbox Code Playgroud)

将在三行上创建一个带有测试的String

此外,你可以通过以下方式使它更整洁:

def a = """test
          |test
          |test""".stripMargin()
Run Code Online (Sandbox Code Playgroud)

stripMargin方法将修剪|每行的左边(包括char)

  • 或者只使用[stripIndent()](http://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/CharSequence.html#stripIndent%28%29)而不是`stripMargin()` . (6认同)
  • 你可以在`"""`字符串中使用双引号 (4认同)
  • 是的,我已经编辑了答案,以展示你需要稍微重新格式化代码以使`stripIndent()`工作. (3认同)
  • 因为a)我已将其作为评论发布,并且b)与此答案没有太大区别. (2认同)

ssc*_*rth 15

类似于stripMargin(),你也可以使用stripIndent()之类的

def a = """\
        test
        test
        test""".stripIndent()
Run Code Online (Sandbox Code Playgroud)

因为

前导空格数最少的行确定要删除的数量.

你还需要缩进第一个"测试"而不是直接在初始化之后"""(\确保多行字符串不以换行符开头).

  • 为了更好地解释,我改进了我的最后一句话. (4认同)
  • 什么是\为什么? (2认同)

cmc*_*nty 12

你可以告诉Groovy语句应该通过添加一对括号来评估结束的行 ( ... )

def a = ("test"
  + "test"
  + "test")
Run Code Online (Sandbox Code Playgroud)

第二种选择是\在每行的末尾使用反斜杠:

def a = "test" \
  + "test" \
  + "test"
Run Code Online (Sandbox Code Playgroud)

FWIW,这与Python多行语句的工作原理相同.

  • 挑剔:Python 多行字符串在使用括号时不需要连接运算符,因此并不完全相同。 (2认同)