ClojureDocs

Nav

Namespaces

set-validator!

clojure.core

Available since 1.0 (source)
  • (set-validator! iref validator-fn)
Sets the validator-fn for a var/ref/agent/atom. validator-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
validator-fn should return false or throw an exception. If the current state (root
value if var) is not acceptable to the new validator, an exception
will be thrown and the validator will not be changed.
2 Examples
user=> (def atm (atom [2]))
#'user/atm

user=> (set-validator! atm #(every? even? %))
nil

user=> (swap! atm into [5])
#<CompilerException java.lang.IllegalStateException: Invalid reference state (NO_SOURCE_FILE:0)>

user=> (set-validator! atm nil)
nil

user=> (swap! atm into [5]))
[2 5]
user=> (def a 1)
#'user/a

user=> (set-validator! (var a) (fn [update-result] (< update-result 3)))
nil

user=> (alter-var-root (var a) inc)
2

user=> (alter-var-root (var a) inc)
IllegalStateException Invalid reference state  clojure.lang.ARef.validate (ARef.java:33)

user=> a
2
See Also

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

Added by kumarshantanu

Creates and returns an agent with an initial value of state and zero or more options (in any order...

Added by kumarshantanu

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

Added by kumarshantanu
1 Note
    By , created 13.1 years ago

    If you want your validator to throw an exception with a useful message, make sure it is a RuntimeException (or subclass), otherwise ARef#validate will throw an IllegalStateException with a generic message.