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

Igor Kolomiets

07/14/2022, 9:56 PM
Is it a bug or a feature?
Copy code
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

07/14/2022, 9:58 PM
the
emptySequence<Int>()
part is irrelevant, you have written something (mostly) equivalent to
Copy code
lateinit var numbers: Sequence<Int>
numbers = sequence {
    yieldAll(numbers)
    yield(1)
}
i

Igor Kolomiets

07/14/2022, 10:02 PM
wow… but still it doesn’t work - an attempt to
Copy code
println(numbers.iterator().next())
still throws StackOverflowError… 😞
e

ephemient

07/14/2022, 10:03 PM
I expected that it would be obvious from my replacement code why it (and your original) don't work
i

Igor Kolomiets

07/14/2022, 10:15 PM
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

07/14/2022, 10:31 PM
it’s a sequence that contains itself
😵 1
n

nkiesel

07/22/2022, 4:46 PM
So just to be crystal clear: your problem is the re-use of the name "number". The following would work w/o problems:
Copy code
fun main() {
    val numbers = emptySequence<Int>()

    val myNumbers = sequence {
        yieldAll(numbers)
        yield(1)
    }

    println(myNumbers.iterator().next())
}
3 Views