简体   繁体   中英

Mutating Java object by using side-effecting method in a loop in Clojure

In my Clojure code I'd like to to use a side-effecting method of Java object in a loop. My intention is to set multiple parameters of the Java object to values that I store in a map:

(def params {
             :param1 "value1"
             :param2 "value2"
             })

If I set param1 to "value1" directly, it works fine:

(.setParam object (str :param1) "value1")

However, if I want to iterate over the params map forcing the evaluation by using doseq , the Java object remains untouched:

(doseq [[param value] params] (.setParam object (str param) value))

How to loop over the params map and use the side-effecting setParam method so that the Java object is mutated?

I believe this is likely a beginner error that would be easy to resolve for more experienced Clojure users.

Calling str on a keyword includes the colon in the result. Try name instead:

(doseq [[param value] params] (.setParam object (name param) value))

It should work, I think you're doing something else wrong.

user=> (def m (java.util.HashMap.))
#'user/m
user=> (doseq [[p v] params] (.put m p v))
nil
user=> m
{:param2 "value2", :param1 "value1"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM