Warning! Strong JAVA radiation!
Lasu2String

30 March 2009

Enhanced while statement proposal

OVERVIEW

FEATURE SUMMARY:
Enhanced while statement allow to iterate through iterator.

MAJOR ADVANTAGE:
People will stop working around for-each loop.

MAJOR BENEFIT(s):
Allow to easy express operation on iterator(s), and iterating over non linear Iterators.

MAJOR DISADVANTAGE:
Automatic loop over Iterator my be problem for some peoples.

ALTERNATIVES:
Using while loop.

EXAMPLES

SIMPLE EXAMPLE:

  String toString(Iterator<String> list){
    if (!list.hasNext()) return "[]";
    StringBuilder ret = new StringBuilder();
    ret.append('[').append(list.next());
    while (String string : list) {
      ret.append(',').append(list.next());  
    }
    return ret.append(']').toString();
  }

ADVANCED EXAMPLE:

  String toString(Iterator<Transfer> list){
    while (Transfer t : list) {
      ArrayList<Data> data = new ArrayList<Data>();
      if ( t.isOpeningTag() )
        while (Transfer t : list){
          if (t.isClosingTag()) break;
          data.add(t.getData());
        }
      else {
        list.remove(); // OK: no interactions
        throw new Exception("...");
        }
      list.remove(); // warning list here can refer to last element of inner loop
      // Process chunk
    }
    
  }
DETAILS

SPECIFICATION:
Same as JLS 14.14.2, except:

  • The Expression must either have type Iterator, or a compile-time error occurs.
  • Let I be the type of the expression Expression

If Expression is directly field or variable or parameter (ExpressionVariable) then additional checking is performed:
If Variable is used as Expression for while-each loop inside while-each loop over same Variable then Variable occurring after inner while-each loop (but in outer while-each loop) will compile with warning “Variable state refer to inner loop”.

COMPILATION:
Same as for-each (almost).

TESTING:
Same as while loops.

LIBRARY SUPPORT:
None.

REFLECTIVE APIS:
No.

OTHER CHANGES:
No.

MIGRATION:
None.

COMPATIBILITY

Except code, which is only forward compatibility.

REFERENCES

Enhanced for each loop iteration control

1 comment: