为什么只有当您不需要返回值时,Groovy 中的括号才是可选的?
例如:
groovy:000> Arrays.asList 1,2,3,4,5
===> [1, 2, 3, 4, 5]
有效,因为不需要该值。
但是当返回值分配给变量时:
groovy:000> a = Arrays.asList 1,2,3,4,5
ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, groovysh_parse: 1: unexpected token: 1 @ line 1, column 19.
a = Arrays.asList 1,2,3,4,5
^
1 error
at java_lang_Runnable$run.call (Unknown Source)
失败。
要使其运行,您需要括号。
groovy:000> a = Arrays.asList( 1,2,3,4,5)
===> [1, 2, 3, 4, 5]
这背后有设计原因吗?或者这只是它的实施方式?
For instance this:
groovy:000> Arrays.asList 1,2,3,4,5
===> [1, 2, 3, 4, 5]
works, because the value is not needed.
But when the return value is assigned to a variable:
groovy:000> a = Arrays.asList 1,2,3,4,5
ERROR org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed, groovysh_parse: 1: unexpected token: 1 @ line 1, column 19.
a = Arrays.asList 1,2,3,4,5
^
1 error
at java_lang_Runnable$run.call (Unknown Source)
Fails.
To make it run you need the parentheses.
groovy:000> a = Arrays.asList( 1,2,3,4,5)
===> [1, 2, 3, 4, 5]
Is there a design reason behind this? Or is it just the way it was implemented?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道历史上的答案,但请注意:
您的示例应该适用于 Groovy 1.8 beta3+
I don't know the answer historically, but note:
Your example should work with Groovy 1.8 beta3+
因为如果没有它们,您将无法将方法调用链接到返回值。 (如果您要链接到单个参数或返回值,则会产生歧义。)
because you would not be able to chain method calls onto the return value without them. (it would be ambiguous if you are to chain to the individual parameter or the return value.)