Limitations of nullability analysis

In the following example the compiler (or IntelliJ) is not able to recognize that x would never be null in the map function:

var x: String? = null
Flux.just("a", null, "b").filter { x != null }.map { x.substring(0) }

(Yes, I know the example is a bit synthetic …)

This is how it looks in IntelliJ:

Would it be possible to recognize such cases correctly?

There is already a function for that: filterNotNull

But that function is sadly not available for Reactor’s Flux. And in my somewhat uncommon example the null check is not releated to elements of the stream. The actual code looks like this:

Flux.interval(timeshift).filter { lastMessage != null }.map { lastMessage }

This is probably a little hack, but it works. In any case it show a limitation of the nullability analysis.

It is the declaration of filter(...) that specifies the return type. What happens in the code passed to it cannot have any influence on the declared type.

If you need this, you can easily add an extension function (based on filterNotNull()) to Flux.

You’re right, there is no chance for the compiler to analyse this. Using an extension function is a good idea although a !! does job (but feels bad).