Is there a way to wrap an iterator inside a custom...
# android
b
Is there a way to wrap an iterator inside a custom iterator? I want to do some logic before returning the values from an iterator, but encapsulate it. A naive approach I tried,
Copy code
myMapObject.asSequence().map {
  yield Pair(it.key, processValue(it.value))
}
but the iterator method
override fun next(): Pair<String, OutputType> {}
doesn't return sequences, but the actual value. My understanding of yield is that it needs to be inside a coroutine, so yield isn't really what im looking for? (im taking cues from the python yield keyword, which is very different)
v
Nowhere in your approach is any iterator involved. And
yield
is not necessary here, it would allow you to produce values for an arbitrary sequence. It is a suspending function, so it has to be called from a suspending function: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/-sequence-scope/yield.html If you for example use the
sequence
function, the lambda you give it is a suspending function, so you can call
yield
in it: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.sequences/sequence.html But as you just want to map the elements of an existing sequence,
yield
is not what you are after, just omit it and you have what you want.
b
Sorry, i omitted the Iterator code, but this currently sits inside
override fun next(): Pair<String, ObjectType> {}
it cant return a sequence, which is why it wont work. I want it to be an iterator so clients can call each item independently. Unless this is also possible with sequences?
v
Sequences are the lazy Kotlin variant of iterators. Much like `Stream`s in Java. https://kotlinlang.org/docs/reference/sequences.html
b
Yes i know, i think asking about sequences was a redherring in my question. thats not my problem/ solution. It was just my first attempt which i discarded My main objective is to wrap an iterator with more logic, and the clients can use this iterator.
Having said that, i might as well change the clients to use a sequence, because i dont know how to encapsulate an iterator with extra logic.
v
There are many ways, at least one indeed involves sequences, like for example
Copy code
myMapObject.asSequence().map { Pair(it.key, processValue(it.value)) }.iterator()
But if your client is using Kotlin, maybe using sequences is actually the better idea.
b
Ohh, thats a nice solution 😃, i was creating a nested Iterator subclass (boiler plate code)… and even that was not working. Thanks