liveBook · Manning

Map as function

As explained in Clojure: The Essential Reference

Map-as-function is Clojure's behavior in which a map can be placed in callable position to look up a key and optionally accept a default value.

A Clojure map can occupy the callable position in a list. Its first argument is the key to look up; an optional second argument supplies a value when that key is absent. section 8.2.2

({:a 1 :b 2} :b) ; #1
;; 2

({:a 1 :b 2} :c "Not found") ; #2
;; "Not found"

The first call returns the value for :b. The second returns "Not found" because :c is absent. section 8.2.2

This is a concise alternative to get. Hash maps implement clojure.lang.IFn for invocation, and both forms ultimately use the clojure.lang.ILookup valAt method. Prefer get when its handling of nil targets or Java maps matters. Keywords can also be invoked, but reverse the argument order: the keyword receives the map. section 8.2.2

How Clojure: The Essential Reference covers it

How deep it goes
Explains key and default arguments, then traces invocation through clojure.lang.IFn to clojure.lang.ILookup valAt.
Examples
Shows a literal map returning 2 for :b and "Not found" for an absent :c.
What it assumes
Assumes familiarity with map literals and keys while explaining how callable-position syntax works.
What you can do after
Apply it via Clojure map invocation to retrieve a key or supply a missing-key default.
How it connects
Relates map invocation to get, keyword invocation, associative lookup, and Java interoperability.

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.