Kotlin allows looping over arrays and anything that “provides an iterator” (via member or extension function iterator()
).
Would it be possible (from a language design perspective) to additionally allow looping over objects that are iterators (i.e. have member of extension functions next()
and hasNext()
)?
Having to wrap an iterator with an iterable (as in Iterable(::children)
) seems needless considering that the loop will only iterate once.
There is already an extension function to iterate over the elements of an iterator using forEach
.
Assuming you want to use objects that do not implement Iterator
but do have the methods of Iterator
, as an iterator, this has been discussed before. The Kotlin team decided not to implement it: "Extension types" for Kotlin. Also see Implicit interfaces as in Go and Implicit interfaces.
You can for
-iterate an Iterator
instance, because there’s an extension Iterator<T>.iterator()
which just returns the Iterator
itself.
If you want to iterate something that is not an Iterator
, but has the required members or extensions next
and hasNext
, you can write the similar extension iterator()
on that type, that just returns the receiver instance itself.
1 Like