Hi OC,

I think that generally speaking, hiding/masking an outer variable like that is a quite undesireable coding style, so I like the current Groovy behavior (even if it deviates from C, evidently - I never used code like that in C, so I did not even know it was valid ;-) ).

What specific use case did you have in mind, where just renaming the inner variable to i0, j, k, ... or the outer to index, idx, ... would not be the better solution ?
(I use an informal coding style where I use variable names with a number at the end for short term / loop / etc variables, and for parameters and variables who live throughout a method or larger block I use no number postfix or longer names; the short name / long name meta at least is quite common, I think)


On 02/12/2020 18:13, OCsite wrote:
Hello there,

when touching this stuff, it would be extremely desirable primarily to fix the scoping/obscuring of same-named variables, which Groovy at the moment does wrong, same as the demented Java thing:

89 ocs /tmp> <q.groovy
def i=0 // outer
println "i=$i (outer)"
for (int i=1 /* inner */;i<2;i++) println "i=$i (inner)"
println "i=$i (outer again)"
89 ocs /tmp> /usr/local/groovy-4.0.0-alpha-1/bin/groovy q
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
/private/tmp/q.groovy: 3: The current scope already contains a variable of the name i
 @ line 3, column 10.
   for (int i=1 /* inner */;i<2;i++) println "i=$i (inner)"
1 error
90 ocs /tmp>

This is how it should work:

90 ocs /tmp> <q.c
#include <stdio.h>
int main() {
  int i=0;
  printf("i=%d (outer)\n",i);
  for (int i=1 /* inner */;i<2;i++) printf("i=%d (inner)\n",i);
  printf("i=%d (outer again)\n",i);
  return 0;
91 ocs /tmp> cc -Wall q.c && ./a.out                     
i=0 (outer)
i=1 (inner)
i=0 (outer again)
92 ocs /tmp> 

Thanks and all the best,

On 2 Dec 2020, at 17:34, Milles, Eric (TR Technology) <eric.milles@thomsonreuters.com> wrote:

Traditional "for" (first example) and ARM "try" (last example) support local variable declarations that are scoped to the statement.  In light of the upcoming "instanceof" enhancement in Java, I was thinking about possible alternatives for declaring local variables that have statement scope.
for (int i = ...; ...) {
  // i available
// i unavailable
for (x in y index i) { // from Gosu (http://gosu-lang.github.io/docs.html) -- an alternative to using eachWithIndex
if (x instanceof T t) { // from Java 14+
if (def x = ...) { // tests Groovy truth in this form; may be wrapped in parens to check something else about "x"
try (def ac = ...) {
This e-mail is for the sole use of the intended recipient and contains information that may be privileged and/or confidential. If you are not an intended recipient, please notify the sender by return e-mail and delete this e-mail and any attachments. Certain required legal entity disclosures can be accessed on our website: https://www.thomsonreuters.com/en/resources/disclosures.html