Thread
#stdlib
    Igor Kolomiets

    Igor Kolomiets

    2 months ago
    Is it a bug or a feature?
    fun main() {
        var numbers = emptySequence<Int>()
    
        numbers = sequence {
            yieldAll(numbers)
            yield(1)
        }
    
        println(numbers.iterator().next()) // throws StackOverflowError
    }
    I do realize that such an approach to build up a sequence may seem unnatural, but for my case (I have to implement Kotlin Serialization’s Encoder interface which methods adds/yields next value for the sequence) I haven’t figured out an alternative.
    e

    ephemient

    2 months ago
    the
    emptySequence<Int>()
    part is irrelevant, you have written something (mostly) equivalent to
    lateinit var numbers: Sequence<Int>
    numbers = sequence {
        yieldAll(numbers)
        yield(1)
    }
    Igor Kolomiets

    Igor Kolomiets

    2 months ago
    wow… but still it doesn’t work - an attempt to
    println(numbers.iterator().next())
    still throws StackOverflowError… 😞
    e

    ephemient

    2 months ago
    I expected that it would be obvious from my replacement code why it (and your original) don't work
    Igor Kolomiets

    Igor Kolomiets

    2 months ago
    oh, so basically, this is expected. I did have feeling that it won’t work due to obviously lazy evaluation of
    numbers
    when it won’t be an empty sequence by the time iterator is created and likely leads to an infinite recursion…
    c

    Chris Lee

    2 months ago
    it’s a sequence that contains itself
    n

    nkiesel

    2 months ago
    So just to be crystal clear: your problem is the re-use of the name "number". The following would work w/o problems:
    fun main() {
        val numbers = emptySequence<Int>()
    
        val myNumbers = sequence {
            yieldAll(numbers)
            yield(1)
        }
    
        println(myNumbers.iterator().next())
    }