java Groovy 方法调用语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28497791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 13:41:57  来源:igfitidea点击:

Groovy method call syntax

javagroovy

提问by Mahesha999

A tutorial heresays:

这里的教程说:

Method calls in Groovy can omit the parenthesis if there is at least one parameter and there is no ambiguity.

Groovy 中的方法调用如果至少有一个参数并且没有歧义,则可以省略括号。

This works:

这有效:

static method1(def val1)
{
    "Statement.method1 : $val1"
}

def method1retval = method1 30; 
println (method1retval);  //Statement.method1 : 30

But when I add another parameter to the method:

但是当我向该方法添加另一个参数时:

static method1(def val1, def val2)
{
    "Statement.method1 : $val1 $val2"
}
def method1retval = method1 30 "20";
println (method1retval);

It gives error

它给出了错误

Exception in thread "main" groovy.lang.MissingMethodException: No signature of method: static Statements.method1() is applicable for argument types: (java.lang.Integer) values: [30]
Possible solutions: method1(int, java.lang.String)

Q.So cant I omit parenthesis when having more than one parameters in method call?

Q.方法调用中有多个参数时,不能省略括号吗?

Q.Also can we omit parenthesis when calling class constructor?

Q.也可以在调用类构造函数时省略括号吗?

回答by cfrick

the call then is method1 30, "20". The docs say you can omit ( and ) but not the ,. In your case the code would be interpreted as method1(30)."20"(do the next call).

然后电话是method1 30, "20"。文档说你可以省略 ( and ) 但不能省略,. 在您的情况下,代码将被解释为method1(30)."20"(进行下一次调用)。

As for constructors in general the same rule applies. But usually they are used with newand this does not work.

对于一般的构造函数,同样的规则适用。但通常它们与 一起使用new,这不起作用。

class A {
    A() { println("X") }
    A(x,y) { println([x,y]) }
}

// new A // FAILS
// new A 1,2 FAILS

A.newInstance 1,2 // works

The errors around newindicate, that a (is expected and that they already fail at parsetime. newis a keyword and holds special behaviour.

周围的错误new表明 a(是预期的,并且它们在解析时已经失败。new是一个关键字并持有特殊行为。

In reality this all comes down to: avoiding the ()to make code nicer (or shorter, if you code-golf). It's primary use is for "DSL" where you would just turn code into readable sentences (e.g. select "*" from "table" where "x>6"or in grails static constraints { myval nullable: true, min: 42 }).

实际上,这一切都归结为:避免()使代码更好(或更短,如果您编写高尔夫球)。它的主要用途是“DSL”,您只需将代码转换为可读的句子(例如select "*" from "table" where "x>6"或在 grails 中static constraints { myval nullable: true, min: 42 })。