问题描述
Groovy 脚本引发错误:
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"
+ "test"
)
为什么?
推荐答案
由于 groovy 没有 EOL 标记(例如 ;
),如果您将运算符放在以下行,它会变得混乱
As groovy doesn't have EOL marker (such as ;
) it gets confused if you put the operator on the following line
这会起作用:
def a = "test" +
"test" +
"test"
因为 Groovy 解析器知道期望在以下行中出现某些内容
as the Groovy parser knows to expect something on the following line
Groovy 将您的原始 def
视为三个独立的语句.第一个将 test
分配给 a
,后两个尝试使 "test"
为正(这是失败的地方)
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)
使用 new String
构造函数方法,Groovy 解析器仍在构造函数中(因为大括号尚未关闭),因此它可以在逻辑上将三行连接到一个语句中
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()
stripMargin
方法 将修剪每一行的左边(直到并包括 |
字符)
这篇关于Groovy 多行字符串有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!