I am aware of the documented behavior of
(defn configure [val & {:keys [debug verbose]
:or {debug false, verbose false}
:as opts}]
(println "val =" val " debug =" debug " verbose =" verbose " opts =" opts))
which binds opts to nil when called via (configure "xxx)
Nevertheless I often would want in this situation, that opts get bound to the default, so {debug false, verbose false}
Is there a way to get this ?Nothing that's built into Clojure. You gotta do some manual processing of opts to merge the default values in.
Something like
(defn configure [val & {:as opts}]
(let [opts (merge-with (fn [v _] v) opts {:debug false :verbose false})]
...))
A related ask: https://ask.clojure.org/index.php/13141/or-destructuring-doesnt-update-objectusually I just merge into a defaults map, then destructure
(defn configure [val & opts]
(let [{:keys [debug verbose]} (merge {:debug false, :verbose false} opts)]
(println "val =" val " debug =" debug " verbose =" verbose " opts =" opts)))
(configure 1)
val = 1 debug = false verbose = false opts = nilcan explicitly bind the "opts with defaults" too if you want to break it apart
and I don't think it's possible to change what :or does now without breaking lots of code. but perhaps something could be added that did this like :defaults, that just did the merge above for you
:and instead of :or :)
I logged a jira https://clojure.atlassian.net/browse/CLJ-2957 for enhancement to keep track of this, feel free to vote on the ask above
Maybe one of the biggest advantage of an "extended" support of this inside the function signature itself, would be to "auto-document" such a 'default', as most IDEs show "full function signatures":
yes
may have interesting entanglements with the upcoming required keys enhancements
Required keys enhancements?
@jason.bullers last clojure dev call dropped some info (caveat, everything is still being designed) about adding something like :keys! destructuring that requires the keys specified (e.g. throws IllegalArgumentException if they are not present). See https://clojurians.slack.com/archives/C06E3HYPR/p1779828764865859
Cool, I'll check that out. Hadn't heard about it before. Thanks!