简体   繁体   中英

Groovy Closure Syntax

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM