atom

added
1.0

ns
clojure.core

type
function

(atom x) (atom x & options)

Creates and returns an Atom with an initial value of x and zero or
more options (in any order):

:meta metadata-map

:validator validate-fn

If metadata-map is supplied, it will become the metadata on the
atom. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception.

                user=> (def my-atom (atom 0))
#'user/my-atom

user=> @my-atom
0

user=> (swap! my-atom inc)
1

user=> @my-atom
1

user=> (swap! my-atom (fn [n] (* (+ n n) 2)))
4

user=> (reset! my-atom 0)
0

user=> @my-atom
0
            
                user=> (def a (atom #{}))
#'user/a

user=>(swap! a conj :tag)
#{:tag}

user=> @a
#{:tag}
            
                user=> (def my-atom (atom 0 :validator even?))
#'user/my-atom

user=> @my-atom
0

user=> (swap! my-atom inc)
IllegalStateException Invalid reference state  clojure.lang.ARef.validate (ARef.java:33)

user=> (swap! my-atom (partial + 2))
2

user=> @my-atom
2