A tutorial here says:
Method calls in Groovy can omit the parenthesis if there is at least one parameter and there is no ambiguity.
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. Also can we omit parenthesis when calling class constructor?
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).
As for constructors in general the same rule applies. But usually they are used with new
and this does not work.
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 new
indicate, that a (
is expected and that they already fail at parsetime. new
is a keyword and holds special behaviour.
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 }
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With