Hey everyone :wave: I am trying to write a "circul...
# announcements
t
Hey everyone 👋 I am trying to write a "circular" iterator that works like so:
Copy code
val it = (1..3).circularIterator()
it.next() // 1
it.next() // 2
it.next() // 3
it.next() // 1
// and so on...
Any ideas how I can accomplish this? Is there already something similar in the stdlib?
d
Copy code
fun <R> Iterable<R>.circularIterator(): Iterator<R> {
    return iterator { 
        while (true) {
            yieldAll(this@circularIterator)
        }
    }
}
Comes to mind
👍 3
You might want to use a
Sequence
instead of an iterator though, in which case you can just replace
iterator { }
with
sequence { }
t
Nice! Works like a charm, thank you!
Why would a
Sequence
be better here?
d
A
Sequence
would allow you to further perform operations on the data (such as
filter
,
map
, etc.) and also allow iterating it multiple times.
t
That makes sense, thanks for the clarification!