Allan Araújo
Allan Araújo

Reputation: 173

How can I pass keywords as arguments that can be passed to update-in?

On the following function:

(defn update-map [state key1 key2] 
    (update-in state [key1 key2] update-fn)
)

If I call the function with:

(update-map state :somekey :otherkey)

I receive a null pointer.

However, if I run the same code of inside the function on the REPL, or substitute the arguments passed to the update-in function to hard keywords, it works flawlessly.

How can I pass keywords as arguments that can be passed to update-in?

Upvotes: 0

Views: 285

Answers (2)

SneakyPeet
SneakyPeet

Reputation: 607

Either state or update-fn is not defined.

You can improve your function to take any amount of keywords using &

(defn update-map [state & ks]
  (update-in state ks update-fn))

Upvotes: 1

Alan Thompson
Alan Thompson

Reputation: 29958

I am guessing you have a (def state ...) somewhere and are confusing the local state in your function with the global state var. This code shows what is happening:

(defn update-fn [some-map key1 key2]
  (update-in some-map [key1 key2] inc ))

(def data {:k1 {:k2 42}})

(update-fn data :k1 :k2) => {:k1 {:k2 43}}

So it works as desired. If it is still not working for you, you'll need to update your question and show how state is defined.

Upvotes: 1

Related Questions