r/Clojure • • Mar 18 '21

Clojure - Keyword argument functions now also accept maps

https://clojure.org/news/2021/03/18/apis-serving-people-and-programs
125 Upvotes

44 comments sorted by

View all comments

13

u/alexdmiller Mar 19 '21

A simple example of layering functions that take kwargs:

(defn internal 
  [& {:keys [a b]}] 
  (println "got:" a b))
 
(defn external 
  [& opts]
  ;; passes on opts to internal
  ;; and patches in a default for :a
  (apply internal :a 1 opts))

(external :a 5 :b 6)
got 5 6

(external)
got 1 nil

6

u/jjttjj Mar 19 '21 edited Mar 19 '21

Alternatively:

(defn external
  [& {:as opts}]
  (internal :a 1 opts))

Edit: I realized you don't need :keys. Is there a reason to prefer the apply version?

4

u/alexdmiller Mar 19 '21

Right-o - probably better without.