1.3.0 permalink Arrow_down_16x16

set-validator!

clojure.core

  • (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.

1 Example top

  • 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]
Log in to add / edit an example.

See Also top

  • 0
    clojure.core/atom

    Creates and returns an Atom with an initial value of x and zero or

  • 0
    clojure.core/agent

    Creates and returns an agent with an initial value of state and zer

  • 0
    clojure.core/ref

    Creates and returns a Ref with an initial value of x and zero or mo

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:2126 top

(defn set-validator!
  "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."
  {:added "1.0"
   :static true}
  [^clojure.lang.IRef iref validator-fn] (. iref (setValidator validator-fn)))
Vars in clojure.core/set-validator!:
Used in 0 other vars

Comments top

1 comment(s) for set-validator!.

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.

Log in to add a comment.