1

If I write

test = {
  println("Hello world");
}

That creates a closure in a variable called test that I can invoke with test();

However

test: {
  println("Hello world");
}

Immediately invokes the closure and I cannot invoke it with test();

What is the purpose of the second syntax?

2 Answers 2

4

That looks like a plain old labeled block of java code. Not Groovy closure syntax. Which would just allow you to scope the local variables within the block. If it is an alternative syntax I would avoid it.

public void do(){
 test:{
   String hello = "hello";
 }

 anotherTest:{
   String hello = "hello";
 }
}
2
  • 1
    It's just a labelled block of code as you say, and not another way of defining a closure. Of course, the OP may have been trying to make a map of closures like: map = [ test:{ println 'Hi' } ] which is a perfectly valid closure definition
    – tim_yates
    Jan 12, 2011 at 16:02
  • 1
    Thank you for the additional insight. I almost deleted my answer after I posted it because I might just be acting as 'Captain Obvious' and not providing any help.
    – Brian
    Jan 12, 2011 at 16:05
1

When doing so, you don't define a closure, but rather label a code block.

Indeed, as this page states, Groovy supports old-school labels.

Yup. it's also a big surprise to me.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.