liveBook · Manning

Missing value

As explained in Clojure: The Essential Reference

nil is Clojure's null value, representing the absence of a value or a null reference.

In Clojure, `nil` represents the absence of a value or a null reference. A missing map value or an unfilled form field can therefore reach a function that cannot handle it. Choose a response based on the job: substitute a default, stop a processing pipeline, or use an operation that accepts `nil`. section 2.2.1 section 2.3.4 section 13.2

Three useful behaviors differ:

  • `fnil` wraps a function and replaces `nil` arguments at specified positions before calling it. It accepts defaults for at most the first three positions. section 2.2.1
  • `some->` and `some->>` stop a threaded computation and return `nil` when a step produces `nil`. They place the preceding result as the next form’s second or last argument, respectively. section 2.3.4
  • `set` accepts a `nil` input collection and returns an empty set. section 13.2

Default or stop?

`(update {:a 1 :b 2} :c inc)` throws a `NullPointerException`; `(update {:a 1 :b 2} :c (fnil inc 0))` returns `{:a 1 :b 2 :c 1}`. If the missing `:c` should instead halt the calculation, `(some-> {:a 1 :b 2} :c inc)` returns `nil`. section 2.2.1 section 2.3.4

How Clojure: The Essential Reference covers it

How deep it goes
Explains positional defaults, a three-default limit, nil-short-circuiting, and set's nil-input result; does not develop nil internals.
Examples
Contrasts a failing map update with fnil and some-> alternatives, and uses an unfilled form field to illustrate defaulting.
What it assumes
Assumes familiarity with Clojure functions and maps while showing how to handle nil in function calls and threaded forms.
What you can do after
Apply it via Clojure's fnil and some-> to default missing arguments or stop a pipeline before a nil-intolerant call.
How it connects
Connects nil handling to fnil, map update, threading macros, Java interop, and set creation.

Also explained in

Compare how 35 books explain missing value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.