Search code examples
clojureclojurescript

Increment a value in of an atom


I am learning clojurescript and i came across this snippet.

:on-click (fn [] (swap! state/order update (:id gig) inc))

I looked up the docs for update function and it said that update takes in a key and a functions. Passes the old value from the atom to the function and then update the atom. If there is no existing value for the key in atom nil is passed as input to the function. When i tried the same thing in the repl it did not work

(def atom-test (atom {}))
(swap! atom-test update :aa inc)
NullPointerException   clojure.lang.Numbers.ops (Numbers.java:1013)

Adding fnil to catch this NullPointerException worked.

user=> (swap! atom-test update :aa (fnil inc 0))
{:aa 1}

I cannot understand why it works in case 1 in clojurescript and why it does not work in case 2 in clojure repl. Can anyone explain whats the trick here.


Solution

  • For cljs, it is common for operations to safely handle nil without causing exceptions.

    cljs.user=> (update {} :a inc)
    {:a 1}
    cljs.user=> (inc nil)
    1
    cljs.user=> (+ 1 nil)
    1
    

    https://cljs.github.io/api/syntax/nil