Limitations of nullability analysis


#1

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?


#2

There is already a function for that: filterNotNull


#3

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.


#4

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.


#5

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).