6

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?

2
  • Definitely legal in java. Commented Dec 9, 2014 at 18:37
  • It must be some issue with Groovy. The same code segment works fine in Java. I'm not too familiar with Groovy myself, but I found the following via a quick google search, and it may help you out: intelligrape.com/blog/multiple-variable-assignment-in-groovy Commented Dec 9, 2014 at 18:37

1 Answer 1

8

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 {
   ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

... Maybe a link would be better until the cut-and-paste does what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.