Groovy method call syntax
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 }
).
Related videos on Youtube
Mahesha999
Updated on June 04, 2022Comments
-
Mahesha999 almost 2 years
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?
-
cfrick about 9 yearsif you can call it with "no ambiguity", yes. but with
new ...
neithernew A
ornew A 1
ornew A 1, 2
work. if you need this for a DSL consider using a builder. chained calls with one param each work well with leaving out (), and builders/fluent apis quite match that. -
Mahesha999 about 9 yearsbut
new A 1,"2"
also doesnt work and there is no ambiguity,1
isint
and"2"
isString
. GettingGroovy:expecting '(' or '[' after type name to continue new expression
-
cfrick about 9 yearswell i could argue, that the problem is the possible interpretation of this code as
new(A)(1,"2")
. but my guess there is, that the keyworknew
has just special behaviour in the language. -
Mahesha999 about 9 yearsok so this applies only to method calls not constructor calls
-
cfrick about 9 yearsno. see my edit.
newInstance
e.g. works. (well, ok, trickery: calling by another way). it just fails fornew