``` operator fun <T> Pair<T, T>.iterat...
# stdlib
h
Copy code
operator fun <T> Pair<T, T>.iterator() = object : Iterator<T> {
    var i = 0
    
    override fun hasNext() = i < 2
    
    override fun next() = when (i++) {
        0 -> first
        1 -> second
        else -> throw NoSuchElementException()
    }
}
p
override fun hasNext() = i <= 1
d
Copy code
operator fun <T> Pair<T, T>.iterator() = sequence {
    yield(first)
    yield(second)
}.toIterator()
h
@PHondogo thank you, fixed
oh, cool
@Dominaezzz how does that compare to my version in terms of performance and safety?
d
Yours will perform better.
Mine might allocate more than one object, not completely sure.
h
I'm not familiar with sequences, so I don't know if they are themselves an object or not
d
There are iterators with different semantics.
Sequences are treated lazily but iterators are treated eagerly.
h
afaik sequences are basically chains of operations on a collection where the full chain is operated on each element before moving to the next
p
Sequence is less performant - you have to allocate object for Sequence + objects/lambdas for each yield, and list to hold them.
c
What's the use case for this?
d
For sequences? Large collections with loads of transformations. Less allocations are made I think.
h
The initial idea was for
Pair
to implement
Iterable
to make generics easier. I admit that now I'm thinking it's more of a "why not?", and because
Iterable
methods are nice. Treating a pair as an iterable is very intuitive, I think, though I think it is wonky that the iterator methods would return
List
and
Iterator
instead of
Pair
So, definitely not one of my better ideas...
d
You can do @Dominaezzz version with
iterator {}
d
Ha, wasn't sure if that was a thing yet.