Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy: use brackets on method calls or not?

Tags:

groovy

this is a fairly general question about whether people should be using brackets on method calls that take parameters or not. i.e.

def someFunc(def p) {
...
}

then calling:

someFunc "abc"

vs...

someFunc("abc")

Is this just a question of consistency, or is there specific use cases for each?

like image 259
Steven Avatar asked Feb 09 '11 02:02

Steven


People also ask

How do you call a method in Groovy?

In Groovy, we can add a method named call to a class and then invoke the method without using the name call . We would simply just type the parentheses and optional arguments on an object instance. Groovy calls this the call operator: () . This can be especially useful in for example a DSL written with Groovy.

Is method in Groovy?

A method is in Groovy is defined with a return type or with the def keyword. Methods can receive any number of arguments. It's not necessary that the types are explicitly defined when defining the arguments. Modifiers such as public, private and protected can be added.

What def means in Groovy?

2. Meaning of the def Keyword. The def keyword is used to define an untyped variable or a function in Groovy, as it is an optionally-typed language.

What is this in Groovy?

" this " in a block mean in Groovy always (be it a normal Java-like block or a Closure) the surrounding class (instance). " owner " is a property of the Closure and points to the embedding object, which is either a class (instance), and then then same as " this ", or another Closure.


3 Answers

It's primarily a question of consistency and readability, but note that Groovy won't always let you get away with omitting parentheses. For one, you can't omit parentheses in nested method calls:

def foo(n) { n }
println foo 1 // won't work

See the section entitled "Omitting parentheses" in the Style guide.

like image 149
Ori Avatar answered Sep 29 '22 18:09

Ori


There's no specific case where you must remove them, you can always use them. It's just prettier to leave them out.
There are cases where you can't do that (where you could confuse a list/map parameter with a subscript operator for instance, nested calls, or when the statement is an assignment), but the general rule is that the outmost call can have no parenthesis if there is no ambiguity.
(deleted several lines, as I've just received notification that there is a post already with that info) Groovy 1.8 will allow even more cases to omit parenthesis, you can check them out at
http://groovyconsole.appspot.com/script/355001

like image 28
jpertino Avatar answered Sep 25 '22 18:09

jpertino


"an empty pair of parentheses is just useless syntactical noise!"

It seems to me that they are encouraging you to use parenthesis when they serve a purpose, but omit them when they are just "noise"

like image 2
benashby Avatar answered Sep 28 '22 18:09

benashby