https://kotlinlang.org logo
#stdlib
Title
# stdlib
h

Hullaballoonatic

07/19/2019, 6:32 PM
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

PHondogo

07/19/2019, 6:39 PM
override fun hasNext() = i <= 1
d

Dominaezzz

07/19/2019, 6:40 PM
Copy code
operator fun <T> Pair<T, T>.iterator() = sequence {
    yield(first)
    yield(second)
}.toIterator()
h

Hullaballoonatic

07/19/2019, 6:40 PM
@PHondogo thank you, fixed
oh, cool
@Dominaezzz how does that compare to my version in terms of performance and safety?
d

Dominaezzz

07/19/2019, 6:41 PM
Yours will perform better.
Mine might allocate more than one object, not completely sure.
h

Hullaballoonatic

07/19/2019, 6:43 PM
I'm not familiar with sequences, so I don't know if they are themselves an object or not
d

Dominaezzz

07/19/2019, 6:43 PM
There are iterators with different semantics.
Sequences are treated lazily but iterators are treated eagerly.
h

Hullaballoonatic

07/19/2019, 6:46 PM
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

PHondogo

07/19/2019, 6:46 PM
Sequence is less performant - you have to allocate object for Sequence + objects/lambdas for each yield, and list to hold them.
c

cbruegg

07/19/2019, 7:04 PM
What's the use case for this?
d

Dominaezzz

07/19/2019, 7:06 PM
For sequences? Large collections with loads of transformations. Less allocations are made I think.
h

Hullaballoonatic

07/19/2019, 7:07 PM
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

Dico

07/19/2019, 7:11 PM
You can do @Dominaezzz version with
iterator {}
d

Dominaezzz

07/19/2019, 7:12 PM
Ha, wasn't sure if that was a thing yet.