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视为三个单独的语句.第一个分配test给a,第二个尝试做出"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)
ssc*_*rth 15
类似于stripMargin(),你也可以使用stripIndent()之类的
def a = """\
test
test
test""".stripIndent()
Run Code Online (Sandbox Code Playgroud)
因为
前导空格数最少的行确定要删除的数量.
你还需要缩进第一个"测试"而不是直接在初始化之后"""(\确保多行字符串不以换行符开头).
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多行语句的工作原理相同.
| 归档时间: |
|
| 查看次数: |
70736 次 |
| 最近记录: |