Threading Through Map Keys in Clojure

An alternative to the `get-in` function.

September 7, 2021

It was wonderful to discover the functional utilities available when working with hashmaps, like assoc, get, update, and their nested friends assoc-in, get-in, and update-in. Just today I discovered an alternative to get-in made possible by the thread-first (->) macro and the fact that map keys are functions on maps.

Some data:

user=> (def stuff {:intro {:hello 42}})

Using get-in:

user=> (get-in stuff [:intro :hello])
42

Using ->:

user=> (-> stuff :intro :hello)
42

Depending on whether you continue threading the results to additional operations you can consider making this even safer using the some-> macro (and the corresponding some->>).

user=> (-> stuff :intro :not-there pos?)
Execution error (NullPointerException) at user/eval158 (REPL:1).
null
user=> (some-> stuff :intro :not-there pos?)
nil