> -----Original Message----- > From: OC [mailto:[email protected]] > Sent: Tuesday, August 18, 2015 2:00 PM > To: [email protected] > Subject: can't declare more variables in a loop? > > Hello there, > > is this a parser bug, or am I overlooking something of importance? > > === > 17 /tmp> <q.groovy > def foo() { > int n=1,m=2; // allright > println "$n $m" > } > def bar() { > for (int n=1,m=2;n<m;n++) println "$n" // oops > } > 18 /tmp> groovy q > org.codehaus.groovy.control.MultipleCompilationErrorsException: > startup failed: > /private/tmp/q.groovy: 6: unexpected token: = @ line 6, column 13. > for (int n=1,m=2;n<m;n++) println "$n" // oops > ^ > > 1 error > > 19 /tmp> groovy -v > Groovy Version: 2.3.8 JVM: 1.7.0_13 Vendor: Oracle Corporation OS: > Mac OS X > 20 /tmp> > === > > Note, incidentally, that Java has this right: > > === > 25 /tmp> <q.java > class q { > public static void main(String[] args) { > for (int n=1,m=2;n<m;n++) System.out.println("-> "+n); > } > } > 26 /tmp> javac q.java && java q > -> 1 > 27 /tmp> > === > > Thanks and all the best, > OC
It is not a parser bug. This is simply one of the few places where Java syntax is not the same as Groovy syntax. You can't have more than one counter variable in a Groovy for loop. However, I'm surprised that this doesn't appear to be mentioned in the Groovy language specification. I would have expected to see it mentioned in http://www.groovy-lang.org/semantics.html in section 1.3.2, "Looping structures", but this only mentions what it DOES support, not what it doesn't.
