Groovy方法调用语法

Mah*_*aha 6 java groovy

这里的教程说:

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

这有效:

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

def method1retval = method1 30; 
println (method1retval);  //Statement.method1 : 30
Run Code Online (Sandbox Code Playgroud)

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

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

它给出了错误

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)
Run Code Online (Sandbox Code Playgroud)

问:在方法调用中有多个参数时,我省略了括号吗?

问:调用类构造函数时我们也可以省略括号吗?

cfr*_*ick 12

然后是电话method1 30, "20".文档说你可以省略(和)而不是,.在您的情况下,代码将被解释为method1(30)."20"(执行下一个调用).

至于构造函数,通常适用相同的规则.但通常它们一起使用,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
Run Code Online (Sandbox Code Playgroud)

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

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