Amir Abiri
Amir Abiri

Reputation: 9417

Kotlin: how to pass a sequence (coroutine) as Iterable<T>

I don't understand how to pass a Coroutine where an Iterable is needed.

Assume I have the following function:

fun <T> iterate(iterable: Iterable<T>) {
    for (obj in iterable) {
        // do something..
    }
}

I want to pass a coroutine:

iterate( ?? {
    for (obj in objects) {
        yield(transform(obj))
    }
})

What am I supposed to put instead of the ?? for this to work? I tried buildIterator and buildSequence but neither one of them work.

Upvotes: 6

Views: 611

Answers (1)

s1m0nw1
s1m0nw1

Reputation: 81929

You can use asIterable():

val seq = buildSequence {
    for (i in 1..5) {
        yield(i)
    }
}.asIterable()

iterate(seq)

Upvotes: 6

Related Questions