[ 
https://issues.apache.org/jira/browse/GROOVY-10683?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17939455#comment-17939455
 ] 

ASF GitHub Bot commented on GROOVY-10683:
-----------------------------------------

daniellansun commented on PR #2169:
URL: https://github.com/apache/groovy/pull/2169#issuecomment-2764351669

   How about `for (int index, var item : items)`?
   For example:
   ```groovy
   // ① traverse a list
   List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
   for (int i, String name : names) {
       System.out.println(i + ": " + name.toUpperCase());
   }
   
   // ② traverse a matrix
   int[][] matrix = {{1,2}, {3,4}};
   for (int row, int[] cols : matrix) {
       for (int col, int val : cols) {
           System.out.printf("[%d,%d]=%d\n", row, col, val);
       }
   }
   
   ```




> Consider enhancing for loop to provide access to loop index or iterator
> -----------------------------------------------------------------------
>
>                 Key: GROOVY-10683
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10683
>             Project: Groovy
>          Issue Type: New Feature
>          Components: parser-antlr4
>            Reporter: Eric Milles
>            Priority: Minor
>
> When iterating over an array or iterable, there is choice between traditional 
> counting loop for index access, declaring/managing an external variable to 
> leverage for-each loop, or switching to {{eachWithIndex}} which requires 
> quite a bit more runtime investment.
> {code:groovy}
> for (int i = 0, n = array.length; i < n; i += 1) {
>   def val = array[i]
> }
> int idx = 0; for (val in array) {
>   idx += 1;
> }
> // idiomatic and takes care of all the management, but lacks STC support for 
> primitive arrays and adds the cost of method invocation for each iteration
> array.eachWithIndex { val, idx ->
> }
> {code}
> Please consider the possibility of {{for}} loop enhancements of 
> [Gosu|https://gosu-lang.github.io/docs.html], which provides a direct syntax 
> for index or iterator:
> {code}
> for (val in array index idx) {
>   println "$idx: $val"
> }
> for (value in iterable iterator iter) { // could be ListIterator for List 
> types, which increases options
>   iter.remove() // for example
> }
> {code}



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to