liveBook · Manning

Set!

As explained in Clojure: The Essential Reference

set! is a Clojure mutation construct that assigns a value to a mutable target such as a field or thread-local binding.

set! is a Clojure mutating macro for assigning a value to a mutable target. It is useful when interoperating with mutable Java objects, changing a thread-bound var, or updating mutable state inside a deftype. section 20.4

Its behavior depends on the target:

  • Write public, non-final static or instance fields on Java classes. section 20.4
  • Mutate a thread-bound var’s current value, never its root value. section 20.4
  • Update mutable fields declared inside deftype definitions. section 20.4
  • Reject ordinary non-dynamic vars and unbound dynamic vars with IllegalStateException. section 20.4

Mutating a Java object

A mutable Java object can be updated through field access: (set! (. p -x) 1) and (set! (. p -y) 2) change a Point from [0 0] to [1 2].

Thread-bound and deftype targets

Bind a dynamic var before assigning it: (binding [*dynamic* 1] (set! *dynamic* 2)) returns 2. A deftype field marked ^:unsynchronized-mutable can likewise be incremented with (set! cnt (inc cnt)).

How Clojure: The Essential Reference covers it

How deep it goes
Defines target-dependent behavior, binding requirements, exceptions, and executable examples, but does not develop implementation internals.
Examples
Demonstrates Point field updates, dynamic-var binding, reflection warnings, and a mutable deftype counter.
What it assumes
Assumes familiarity with Clojure forms, vars, binding, Java fields, and deftype; distinguishes valid mutable targets from ordinary vars.
What you can do after
Apply it via Clojure to supported mutable targets and recognize binding errors or risky mutable-object usage.
How it connects
Connects mutation with Java interoperability, dynamic variables, thread-local bindings, deftype, and side effects.

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.