liveBook · Manning

Boxing

As explained in Clojure: The Essential Reference

Autoboxing is the implicit conversion of primitive values to object representations and, where applicable, the reverse conversion.

Boxing wraps a native primitive value in its corresponding reference class, such as converting a primitive long into a java.lang.Long. Clojure may perform this conversion implicitly when generated code passes primitive values to functions expecting Object arguments. section 6.5

Boxing can change reference identity

Vars can preserve one reference: (def a 1000) (def b a) (identical? a b) returns true. Local primitive values can instead be boxed separately: (let [x 1000 y x] (identical? x y)) returns false. Thus identical? can expose boxing behavior; use = when testing equivalence rather than reference identity. section 6.5

Explicit construction also matters: (identical? (Long. 100) 100) returns false. Long/valueOf can consult Java’s numeric cache, but cached identity is limited and should not replace value-based comparison. section 6.5

How Clojure: The Essential Reference covers it

How deep it goes
Traces implicit boxing into generated Object arguments and contrasts it with constructors, cached valueOf calls, and variable bindings.
Examples
Uses 100 and 1000 Long values, def and let bindings, Long constructors, and Long/valueOf to expose identity differences.
What it assumes
Assumes primitive and reference types, Java classes, Clojure bindings, and the distinction between identity and equality.
What you can do after
Diagnose reference-identity surprises caused by boxing and choose value-based comparison when equivalence is intended.
How it connects
Connects boxing with identical?, reference equality, Java numeric caching, and value-based equality through = and ==.

Also explained in

Compare how 3 books explain boxing →

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.