An SO User
An SO User

Reputation: 25008

How many parentheses can I skip in Groovy?

I am new to Groovy and while reading the book Groovy in Action, I learned that I can skip the parentheses that we use in Java to enclose the arguments. Fine. To test that out I wrote a simple Groovy script (program isn't the right word, is it ?)

Here it is:

import java.text.*
DateFormat fmt = DateFormat.getDateTimeInstance()
println fmt.format(new Date())  

This runs perfect. However, when I remove the parentheses around the new Date(), I get an error that:

Exception thrown

groovy.lang.MissingPropertyException: No such property: format for class: java.text.SimpleDateFormat 
    at ConsoleScript8.run(ConsoleScript8:3)  

What is going wrong? Why can't I skip those parentheses ?

Upvotes: 0

Views: 726

Answers (1)

Will
Will

Reputation: 14539

Because Groovy parses code missing parenthesis considering the first call as a method on this object. So when you write:

println fmt.format new Date()

Groovy parses into:

println(fmt.format).new Date()

This will give an error stating you are missing a format property for the class java.text.SimpleDateFormat.

Take this example:

e = new Expando()
e.format = {
  "format called"
}

def foo = {
  println it
  it()
}

foo e.format new Date()

The result will be:

MissingPropertyException: No such property: Wed Nov 20 10:05:32 2013 for class: java.lang.String

Groovy understands it as:

print( e.format ).new Date()

So it is trying to get the property new Date() from the result of the print() function.


For a simple date formatting, you can just use the Date.format method:

println new Date().format("yyyy-MM-dd") 

As for Groovy rules, take this example into account:

drink tea with sugar and milk

What Groovy understand is:

drink(tea).with(sugar).and(milk)

Very good for DSLs ;-).

Upvotes: 3

Related Questions