为什么从函数返回的 gstring 串联是空字符串 - Groovy 1.7.4
我有以下代码:
public class TestGr
{
static String aaa = "wwww";
public static void main(args)
{
println "["+getAAA()+"]";
println "[" + getBBB() +"]";
}
static String getAAA()
{
return ""
+ "${aaa}"
}
static String getBBB()
{
return "" + "${aaa}"
}
}
该代码的输出是:
[]
[wwww]
我不明白为什么在第一次调用中我得到一个空字符串。有谁知道为什么换行符会改变函数的输出?
I have the following code:
public class TestGr
{
static String aaa = "wwww";
public static void main(args)
{
println "["+getAAA()+"]";
println "[" + getBBB() +"]";
}
static String getAAA()
{
return ""
+ "${aaa}"
}
static String getBBB()
{
return "" + "${aaa}"
}
}
The output of this code is:
[]
[wwww]
I do not understand why in the first call I get an empty string. Does anybody know why a line break change the output of a function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这就是 groovy 被解析的方式。由于语句末尾的分号是可选的,换行符有时会产生影响。
getAAA() 被解析为两个语句,如下所示:
尽管一元
+
运算符对于字符串 arg 没有意义,但由于其动态特性,groovy 无法捕获它。字符串上可能有一个postive()
元方法,可以使其有效。编辑:
为了更好地了解发生的情况,启动 groovyConsole 并加载脚本。从脚本菜单中选择“检查 AST”。您会看到类似这样的内容:
It's the way the groovy is being parsed. Since semicolons at the end of statements are optional, newlines sometimes make a difference.
getAAA() is being parsed as two statements, like this:
Even though the unary
+
operator doesn't make sense with a string arg, groovy can't catch it due to its dynamic nature. There might be apostive()
meta method on string that would make it valid.EDIT:
For a better idea of what's going on, start up
groovyConsole
and load your script. Select "Inspect AST" from the Script menu. You'll see something like this: