Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy: colon mark in closure?

Tags:

groovy

I am trying to make my own Dsl and was playing around with different styles of closures in groovy. I've stumbled upon follwing snippet:

myClosure {
  testProperty: "hello!"
}

But can't figure out if this a valid code and how can I access then this testProperty. Is it valid? How can I read "hello!" value?

like image 929
Igor Konoplyanko Avatar asked Sep 19 '25 19:09

Igor Konoplyanko


1 Answers

For now, lets put aside closures, consider the following code:

def f1() {
  testProperty : 5  
}
def f2() {
  testProperty : "Hello"
}
println f1()
println f1().getClass()
println f2()
println f2().getClass()

This compiles (therefor the syntax is valid) and prints:

5
class java.lang.Integer
Hello
class java.lang.String

So what you see here is just a labeled statement (groovy supports labels see here)

And bottom line the code of f1 (just like f2) is:

def f1() {
  return 5 // and return is optional, so we don't have to write it
}

With closures its just the same from this standpoint:

​def method(Closure c) {
  def result = c.call()
  println result
  println result.getClass()
}

method {
   test : "hello"
}

This prints

hello
class java.lang.String

as expected

like image 55
Mark Bramnik Avatar answered Sep 21 '25 14:09

Mark Bramnik