Jonathan Ellis
06/03/2022, 3:14 PMoperator fun Body.iterator(): Iterator<Body> {
val body = this
return object : Iterator<Body> {
var current: Body? = body
override fun hasNext(): Boolean {
return current != null
}
override fun next(): Body {
val result = current!!
current = result.getNext()
return result
}
}
}
Chris Lee
06/03/2022, 3:15 PMthis@iterator
or similar to get you back to the enclosing method.mkrussel
06/03/2022, 3:19 PMnext
function is throwing the wrong exception based on the contract from Java. Kotlin has no contract on what to do if next
cannot return anything.Joffrey
06/03/2022, 3:21 PMSequence
instead, so you don't have to deal with the iterator interface yourselffun Body.asSequence(): Sequence<Body> = sequence {
var current: Body? = this@asSequence
while(current != null) {
yield(current)
current = current.getNext()
}
}
https://pl.kotl.in/Uk-KSmcQLJonathan Ellis
06/03/2022, 5:15 PMJoffrey
06/03/2022, 5:21 PMiterator()
operator with asSequence().iterator()
but you may as well just implement it directly like you just did.Sam
06/06/2022, 7:41 AMiterator { ... }
builder that works exactly like the sequence { ... }
builder.Joffrey
06/06/2022, 8:00 AMSam
06/06/2022, 8:07 AMsequence { ... }
is just = Sequence { iterator(block) }
.Joffrey
06/06/2022, 8:59 AMfor
loops, so I rarely implement the iterator
operator. And mutating a list while iterating is something I haven't had to use in Kotlin at all (for years), and this was the main reason to use iterators directly