liveBook · Manning

Identity

As explained in Clojure: The Essential Reference

Object identity is the property of an object being the specific allocated instance referenced by a value rather than merely an object with equal contents.

Object identity asks whether two values refer to one specific allocated instance, rather than merely containing equal data. Clojure exposes this test through identical?. Equality primarily compares values, while types can add semantic distinctions; identity compares the instance itself. section 6.0 section 6.5

identical? accepts exactly two arguments of any type, including nil, and returns true only when both references designate the same object instance. Supplying any other arity raises clojure.lang.ArityException. section 6.5

Use identity deliberately rather than as a replacement for ordinary equality:

  • Use = when logically equal values should compare equal, even when collections have different concrete types. section 6.0
  • Use identical? when a particular instance carries meaning, such as a unique sentinel used to stop a consumer loop. section 6.5
  • Interpret results carefully because interning can make separately written basic values share an instance, producing surprising true results. section 6.5

A private sentinel

Create a unique object and have both producer and consumer recognize that exact instance: (def SENTINEL (Object.)) (if (identical? SENTINEL event) (println "done") (process event)) A separately created object is not the sentinel, even if it has the same role or contents. This lets a daemon-like consumer distinguish a stop signal from ordinary business data. section 6.5

Bindings and instances

Two bindings can point to one object: (let [x #{1 2 3} y x] (identical? x y)) ;; true By contrast, independently produced values may not share identity, even when they print alike. Java value construction and caching can change the result, so identity is not a general-purpose value comparison.

How Clojure: The Essential Reference covers it

How deep it goes
Defines the two-argument contract, arity failure, sentinel use, bindings, and interning surprises without detailing runtime allocation internals.
Examples
Demonstrates shared bindings, queue sentinels, cached values, independently constructed numbers, and basic-type interning.
What it assumes
Builds from comparisons among values and types before distinguishing identity as a separate comparison property.
What you can do after
Apply it via identical? to recognize a unique sentinel or verify that two bindings reference one instance.
How it connects
Connects object identity with equality, types, reference equality, interning, Java objects, and sentinel values.

Also explained in

Compare how 8 books explain identity →

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.