Use foreach to iterate using an Iterator
When the foreach syntax (for(:)) has been introduced in 1.5, a recurring question was why foreach is not able to iterate using an iterator.
I think i have a trick to do that using the syntax of the closure :
Iterator<String> scanner=new Scanner(System.in);
for(String word:() { scanner })
System.out.println(word);
Why this code works. The foreach statement needs an array or an object that implements java.lang.Iterable. Iterable is an interface that has a single method iterator that returns an iterator thus the closure convertion is applicable.
Rémi
- Printer-friendly version
- forax's blog
- 3462 reads





