Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to create a map dynamically

Tags:

clojure

I wonder, why does this crash?

(defn test1 [var1 & var2]
  (print (json/write-str (merge {:key1 var1} var2))))

(defn -main [& args]
  (test1 "val1" {:key2 "val2" :key3 "val3"}))

The error is:

Exception in thread "main" java.lang.ClassCastException: clojure.lang.PersistentArrayMap cannot be cast to java.util.Map$Entry,  
like image 624
Alan Coromano Avatar asked Mar 23 '26 18:03

Alan Coromano


1 Answers

Your parameter var2 actually contains Rest Arguments (it comes after the & character). So it actually contains all the arguments that come after var1. You can fix the code by removing the &, but then you can only specify a single var2 argument:

(defn test1 [var1 var2]
  (print (json/write-str (merge {:key1 var1} var2))))

If you want to be able to pass multiple maps as var2, you first have to merge them into a single map:

(defn test1 [var1 & var2]
  (print (json/write-str (merge {:key1 var1} 
                                (apply merge var2)))))
like image 126
David Tanzer Avatar answered Mar 25 '26 17:03

David Tanzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!