For-loop with multiple variable declarations

I am 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 is not allowed?

+6
source share
1 answer

This is the normal version for Java developers. See link for more details:

General errors you can use only one variable count .

Excerpts from the link:

for cycles

Another small difference is that you cannot initialize more than one variable in the first part of the for loop, so this is not true:

 for (int count = someCalculation(), i = 0; i < count; i++) { ... } 

and you will 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 can just skip the for and use time loop:

 someCalculation().times { ... } 
+7
source

Source: https://habr.com/ru/post/979351/


All Articles