Groovy多行字符串有什么问题? [英] What's wrong with Groovy multi-line String?
问题描述
pre $
def a =test
+test
+test
错误:
没有方法签名: >
虽然此脚本正常工作:
def a = new String(
test
+test
+test
)
为什么?
由于groovy没有EOL标记(比如;
)如果你把操作符放在下面的行中,它会很困惑
这可以用来代替:
def a =test+
test+
test
$因为Groovy解析器知道在下面一行有所期待:
Groovy将您的原始 def
看作三个单独的语句。第一个将 test
分配给 a
,第二个尝试使test
positive(这是失败的地方)
使用新的String
构造方法, Groovy解析器仍然在构造函数中(因为大括号尚未关闭),所以它可以逻辑地将三条线连接在一起成为一个语句
在线字符串中,您也可以使用三元引用:
def a =test
test
测试
将在三行上创建一个包含测试的字符串
另外,你可以通过以下方式使它更整洁:
def a =test
| test
| test。stripMargin()
stripMargin
方法将修剪左边(直至并包括 | $) c $ c> char)从每行
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?
解决方案 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
这篇关于Groovy多行字符串有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!