试图动态创建地图

时间:2016-01-11 07:13:07

标签: clojure

我想知道,为什么这会崩溃?

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

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

错误是:

Exception in thread "main" java.lang.ClassCastException: clojure.lang.PersistentArrayMap cannot be cast to java.util.Map$Entry,  

1 个答案:

答案 0 :(得分:2)

您的参数var2实际上包含Rest Arguments(它位于&字符之后)。所以它实际上包含了var1之后的所有参数。您可以通过删除&来修复代码,但之后只能指定一个var2参数:

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

如果您希望能够将多个地图作为var2传递,则首先必须将它们合并到一个地图中:

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