简体   繁体   English

Groovy 中的匿名代码块

[英]Anonymous code blocks in Groovy

Is there a way to use anonymous code blocks in Groovy?有没有办法在 Groovy 中使用匿名代码块? For example, I'm trying to translate the following Java code into 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”的变量也是一种反模式,因此对于我正在处理的这段代码,匿名代码块会有所帮助。

You can use anonymous code blocks in Groovy but the syntax is ambiguous between those and closures.您可以在 Groovy 中使用匿名代码块,但这些代码块和闭包之间的语法不明确。 If you try to run this you actually get this error:如果您尝试运行它,您实际上会收到此错误:

Ambiguous expression could be either a parameterless closure expression or an isolated open code block;歧义表达式可以是无参数的闭包表达式,也可以是孤立的开放代码块; solution: Add an explicit closure parameter list, eg {it -> ...}, or force it to be treated as an open block by giving it a label, eg 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
1.times {
    // I'm like a block.
}

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 安装,但应该可以。

In Groovy, those braces constitute a closure literal.在 Groovy 中,这些大括号构成了一个闭包字面量。 So, no can do.所以,没有办法。 Personally, I'd consider having to give up anonymous blocks for getting closures a very good deal.就个人而言,我会考虑放弃匿名块以获得非常好的关闭。

The most common need for an anonymous block is for additional (possibly shadowing) bindings using def .对匿名块的最常见需求是使用def进行附加(可能隐藏)绑定。 One option is to create a dictionary equivalent of your bindings and use .with .一种选择是创建一个与绑定等效的字典并使用.with Using the example given in the question:使用问题中给出的示例:

[i:0].with {
  println i
}

int i = 10
println i

This gives you a lisp styled let block这给了你一个 lisp 风格的let

Why not just add if(true)为什么不添加if(true)

if(true) {
  int i = 0;
  System.out.println(i);
}
int i = 10;
System.out.println(i);

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

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