开发者

Groovy Closure Syntax

开发者 https://www.devze.com 2023-02-03 16:45 出处:网络
If I write test = { println(\"Hello world\"); } That creates a closure in a variable called test that I can invoke with test();

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 wor开发者_运维问答ld");
}

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

What is the purpose of the second syntax?


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";
 }
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消