Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous code blocks in Groovy

Tags:

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

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.

like image 706
piepera Avatar asked Apr 19 '10 20:04

piepera


People also ask

What are closures in Groovy?

A closure in Groovy is an open, anonymous, block of code that can take arguments, return a value and be assigned to a variable. A closure may reference variables declared in its surrounding scope.

What is the use of anonymous block in Java?

An anonymous block is used when you want to execute some common statements before all the constructors that are available in a class. As you can see the statement of the anonymous block is executed before the constructor.

How do you make a closure on Groovy?

Closures can also contain formal parameters to make them more useful just like methods in Groovy. In the above code example, notice the use of the ${param } which causes the closure to take a parameter. When calling the closure via the clos. call statement we now have the option to pass a parameter to the closure.

What is assert Groovy?

An assertion is similar to an if, it verifies the expression you provide: if the expression is true it continues the execution to the next statement (and prints nothing), if the expression is false, it raises an AssertionError.


2 Answers

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:

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

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
like image 83
Chris Dail Avatar answered Nov 10 '22 00:11

Chris Dail


1.times {
    // I'm like a block.
}
like image 25
Bob Herrmann Avatar answered Nov 10 '22 00:11

Bob Herrmann