I'm pretty sure the following is legal in Java
for (int var1 = 2, var2 = 3; var1 < 10; ++var1) {
System.out.println(var1);
}
But when I try to run it in the Groovy console, I get this error
unexpected token: =
Are multiple variable declarations unsupported by Groovy or is there another reason why this isn't allowed?
Every declaration should be for a single variable, on its own line, with an explanatory comment about the role of the variable. Declaring multiple variables in a single declaration can cause confusion regarding the types of the variables and their initial values.
With two arguments in the range function, the sequence starts at the first value and ends one before the second argument. Programmers use x or i as a stepper variable.
Often the variable that controls a for loop is needed only for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for.
Can you have 2 variables in a for loop Python? By using zip() and enumerate(), we can iterate with two variables in a for loop. We can also iterate with two elements in a dictionary directly using for loop.
It's a common gotcha for Java Developers. See this link for more detail:
Common gotchas you can use only one count variable.
Excerpts from the link:
for Loops
Another small difference is that you can’t initialize more than one variable in the first part of a for loop, so this is invalid:
for (int count = someCalculation(), i = 0; i < count; i++) { ... }
and you’ll need to initialize the count variable outside the loop (a rare case where Groovy is more verbose than Java!):
int count = someCalculation() for (int i = 0; i < count; i++) { ... }
or you could just skip the whole for loop and use times:
someCalculation().times { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With