java Groovy 中的匿名代码块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2670785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Anonymous code blocks in Groovy
提问by piepera
Is there a way to use anonymous code blocks in Groovy? For example, I'm trying to translate the following Java code into Groovy:
有没有办法在 Groovy 中使用匿名代码块?例如,我正在尝试将以下 Java 代码转换为 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
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.
我知道匿名代码块通常是一种反模式。但是具有名称如“inputStream0”和“inputStream1”的变量也是一种反模式,因此对于我正在处理的这段代码,匿名代码块会有所帮助。
回答by Chris Dail
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 中使用匿名代码块,但这些代码块和闭包之间的语法不明确。如果您尝试运行它,您实际上会收到此错误:
Ambiguous expression could be either a parameterless closure expression or an isolated open code block; solution: Add an explicit closure parameter list, e.g. {it -> ...}, or force it to be treated as an open block by giving it a label, e.g. L:{...} at line: 1, column: 1
歧义表达式可以是无参数的闭包表达式,也可以是孤立的开放代码块;解决方案:添加一个明确的闭包参数列表,例如{it -> ...},或者通过给它一个标签来强制将其视为一个开放块,例如 L:{...} at line: 1, column: 1
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:
按照建议,您可以使用标签,它将允许您使用匿名代码块。用 Groovy 重写 Java 代码:
l: {
int i = 0
println i
}
int i = 10
println i
回答by Bob Herrmann
1.times {
// I'm like a block.
}
回答by OscarRyz
What about:
关于什么:
({
int i = 0
println i
}).()
int i = 10
println i
I don't have a Groovy installation at hand, but that should do.
我手头没有 Groovy 安装,但应该可以。
回答by Michael Borgwardt
In Groovy, those braces constitute a closure literal. So, no can do. Personally, I'd consider having to give up anonymous blocks for getting closures a very good deal.
在 Groovy 中,这些大括号构成了一个闭包字面量。所以,没有办法。就个人而言,我会考虑放弃匿名块以获得非常好的关闭。
回答by Marty Neal
The most common need for an anonymous block is for additional (possibly shadowing) bindings using def. One option is to create a dictionary equivalent of your bindings and use .with. Using the example given in the question:
匿名块最常见的需求是使用def. 一种选择是创建一个与您的绑定等效的字典并使用.with. 使用问题中给出的示例:
[i:0].with {
println i
}
int i = 10
println i
This gives you a lisp styled letblock
这给你一个 lisp 风格的let块

