简体   繁体   English

Groovy闭包语法

[英]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(); 这将在名为test的变量中创建一个闭包,我可以使用test();进行调用test();

However 然而

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

Immediately invokes the closure and I cannot invoke it with test(); 立即调用闭包,而我不能使用test();来调用它test();

What is the purpose of the second syntax? 第二种语法的目的是什么?

That looks like a plain old labeled block of java code. 看起来像是一个普通的带有标签的Java代码块。 Not Groovy closure syntax. 不是Groovy闭包语法。 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. 的确,正如该页面所述 ,Groovy支持老式标签。

Yup. 对。 it's also a big surprise to me. 这对我来说也是一个很大的惊喜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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