Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy optional parentheses and dots

Tags:

groovy

dsl

I am learning Groovy and am pretty impressed with how it allows one to build a intelligent DSL, but I am a bit confused by the rules for when parentheses and dots are optional. Consider the following code:

Integer take(Integer x) {x}
take 3 plus 4

This works as expected and produces an output of 7 (when ran in the console), as groovy understands that last line as take(3).plus(4).

Now, println take 3 plus 4 does not work as groovy understands that as println(take).3(plus).4 which is nonsense.

Every example that I am seeing shows these sort of expression by themselves on a line, but apparently

s = take 3 plus 4

works and stores the result 7 in s. My question is, why does

println( take 3 plus 4 )

not work? Obviously, groovy will parse these sort of expressions even if they are not by themselves on a line (as shown by the assignment working). I would have thought that adding those parentheses would remove the ambiguity from the form of that line that doesn't work and that it would print out 7 as I intended.

Instead groovy gives an error 'unexpected token: 3'. As far as I can tell, groovy will not allow optional parentheses or dots inside that println, even though it doesn't seem to be ambiguous. When exactly does this sort of trick work?

like image 627
Matthew Avatar asked Jan 10 '16 21:01

Matthew


People also ask

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

Does Groovy need semicolons?

​ semicolons are optional in Groovy, you can omit them, and it's more idiomatic to remove them.

What is def call 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.


1 Answers

This falls into the category of a nested method call, and in that case you cannot omit the parentheses. This is causing ambiguity and the results are unexpected, as the println method thinks you are passing it multiple parameters. You could reduce the ambiguity by using a groovy string in the println method.

println "${take 3 plus 4}"

More info: Omit Parentheses

like image 163
dspano Avatar answered Jan 03 '23 00:01

dspano