@BuilderInference and smart casts - should it work?

I have a function foo which doesn’t compile. It generates sequence (like generateSequence). The while condition s != null should smart cast s from T? to T but it’s not the case because seq has type Sequence<T?>.

My second point is when I add !! and write yield(s!!) the code compiles but compiler warns Unnecessary non-null assertion.

My question is whether it’s possible to make it work without !! and without adding type annotation to sequence call - because that’s why it uses @BuilderInference or how is @BuilderInference supposed to work?

fun <T : Any> foo(seed: T?, next: (T) -> T?): Sequence<T> {
    val seq = sequence {
        var s = seed
        while (s != null) {
            yield(s)
            s = next(s)
        }
    }
    return seq
}

Looks like a bug that is already fixed in 1.4-M3.
If you don’t want to upgrade to an unstable version of kotlin you can use
sequence<T> { ... }. That way everything should work.