Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 625
Amir Abiri Avatar asked Dec 22 '17 10:12

Amir Abiri


1 Answers

You can use asIterable():

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

iterate(seq)
like image 83
s1m0nw1 Avatar answered Nov 15 '22 09:11

s1m0nw1