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)).
