Thread
#stdlib
    Hullaballoonatic

    Hullaballoonatic

    3 years ago
    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

    3 years ago
    override fun hasNext() = i <= 1
    Dominaezzz

    Dominaezzz

    3 years ago
    operator fun <T> Pair<T, T>.iterator() = sequence {
        yield(first)
        yield(second)
    }.toIterator()
    Hullaballoonatic

    Hullaballoonatic

    3 years ago
    @PHondogo thank you, fixed
    oh, cool
    @Dominaezzz how does that compare to my version in terms of performance and safety?
    Dominaezzz

    Dominaezzz

    3 years ago
    Yours will perform better.
    Mine might allocate more than one object, not completely sure.
    Hullaballoonatic

    Hullaballoonatic

    3 years ago
    I'm not familiar with sequences, so I don't know if they are themselves an object or not
    Dominaezzz

    Dominaezzz

    3 years ago
    There are iterators with different semantics.
    Sequences are treated lazily but iterators are treated eagerly.
    Hullaballoonatic

    Hullaballoonatic

    3 years ago
    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

    3 years ago
    Sequence is less performant - you have to allocate object for Sequence + objects/lambdas for each yield, and list to hold them.
    cbruegg

    cbruegg

    3 years ago
    What's the use case for this?
    Dominaezzz

    Dominaezzz

    3 years ago
    For sequences? Large collections with loads of transformations. Less allocations are made I think.
    Hullaballoonatic

    Hullaballoonatic

    3 years ago
    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...
    Dico

    Dico

    3 years ago
    You can do @Dominaezzz version with
    iterator {}
    Dominaezzz

    Dominaezzz

    3 years ago
    Ha, wasn't sure if that was a thing yet.