I can explain why it is not called, but I cannot offer a solution: Your sequence is frozen at yield(2). Kotlin has no way of knowing it must exit at that point (i.e. you don’t (and can’t?) send a signal to the sequence telling it to terminate), and invoke the finally block.
I can understand abandoned coroutines should be avoided (like aborting threads) but a major feature of lazy sequences are that they can be “abandoned”.
This makes me wonder if try..finally should be forbidden in buildSequence to avoid confusion that may lead to file, mutex lock and connection leaks.
The yield() call could happen from a closure and the code calling the closure could wrap that in a try-finally. I don’t think there’s a way to statically analyse this all at compile-time.
Is it possible to dynamically check this at runtime, in the generated byte-code?