问题描述
有没有办法在Groovy中使用匿名代码块?例如,我试图将下面的Java代码翻译成Groovy:
Is there a way to use anonymous code blocks in Groovy? For example, I'm trying to translate the following Java code into Groovy:
{
int i = 0;
System.out.println(i);
}
int i = 10;
System.out.println(i);
我能想到的最接近的翻译如下:
The closest translation I can come up with is the following:
boolean groovyIsLame = true
if (groovyIsLame) {
int i = 0
println i
}
int i = 10
println i
我知道匿名代码块通常是一种反模式。但是,像inputStream0和inputStream1这样的名称变量也是一个反模式,所以对于我正在处理的代码,匿名代码块会有帮助。
I know anonymous code blocks are often kind of an antipattern. But having variables with names like "inputStream0" and "inputStream1" is an antipattern too, so for this code I'm working on, anonymous code blocks would be helpful.
推荐答案
您可以在Groovy中使用匿名代码块,但是这些和闭包之间的语法不明确。如果你试图运行这个函数,你实际上会得到这个错误:
You can use anonymous code blocks in Groovy but the syntax is ambiguous between those and closures. If you try to run this you actually get this error:
按照建议,您可以使用标签,它将允许您使用匿名代码块。在Groovy中重写Java代码:
Following the suggestion, you can use a label and it will allow you to use the anonymous code block. Rewriting your Java code in Groovy:
l: {
int i = 0
println i
}
int i = 10
println i
这篇关于Groovy中的匿名代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!