问题描述
有没有办法在 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:
歧义表达可以是无参数闭包表达式或隔离的开放代码块;解决方案:添加显式闭包参数列表,例如{it -> ...},或者强制它通过给出被视为一个开放块它是一个标签,例如L:{...} 在第 1 行,列:1
按照建议,您可以使用标签,它将允许您使用匿名代码块.在 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 中的匿名代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!