I'm reading some Clojure code at the moment that has a bunch of uninitialised values as nil
for a numeric value in a record that gets passed around.
Now lots of the Clojure libraries treat this as idiomatic. Which means that it is an accepted convention.
But it also leads to NullPointerException
, because not all the Clojure core functions can handle a nil
as input. (Nor should they).
Other languages have the concept of Maybe
or Option
to proxy the value in the event that it is null, as a way of mitigating the NullPointerException
risk. This is possible in Clojure - but not very common.
You can do some tricks with fnil
but it doesn't solve every problem.
Another alternative is simply to set the uninitialised value to a symbol like :empty-value
to force the user to handle this scenario explicitly in all the handling code. But this isn't really a big step-up from nil
- because you don't really discover all the scenarios (in other people's code) until run-time.
My question is: Is there an idiomatic alternative to nil-punning in Clojure?