Best practices for dealing with `Union{Nothing,...}`

I also want to add that difference in inference of isnothing vs === nothing also applies to missing (which is a singleton as well). Keno explains why that’s the case in ismissing(x) much slower than x === missing · Issue #27681 · JuliaLang/julia · GitHub

=== is special in inference and inference happens before inlining

Note that isa is also special; so x === nothing should also be as good as x isa Nothing.

Regarding monadic style, I don’t think it is regarded as “bad” in Julia. For example, there is a discussion about adding a special syntax to lift a function on Union{T, Missing}: Status of question mark syntax for missing values - #2 by StefanKarpinski

But my impression is writing something like

i1 = findfirst(isequal(c1), labels1)
i1 === nothing && return nothing
i2 = findfirst(isequal(c2), labels2)
i2 === nothing && return nothing
return (i1, i2)

is more common. This is so common that IterTools.jl has @ifsomething which can be used to write

i1 = @ifsomething findfirst(isequal(c1), labels1)
i2 = @ifsomething findfirst(isequal(c2), labels2)
return (i1, i2)

This expands to something like above.

5 Likes