aav
aav

Reputation: 2489

provide default value in clojure.spec

Is there a way to specify default values for keys mentioned in (s/keys :opt [::k1 ::k2])?

Something like:

(s/keys :opt [(with-default ::k1 "default1") (with-default ::k2 "default2")])

Or it is more idiomatic to handle default values outside of clojure.spec?

Upvotes: 4

Views: 721

Answers (2)

Alex Miller
Alex Miller

Reputation: 70201

There is no explicit feature for this in spec and I would expect you to handle it in the code, not in the spec.

It is possible to build something that does this with s/conformer, but I would not consider that a recommended use of that feature.

Upvotes: 2

Michiel Borkent
Michiel Borkent

Reputation: 34800

I don't think so, as clojure.spec is mainly concerned with data validation and structure, not with enriching, coercing or changing data. So you would have to do it yourself. E.g.:

(merge {::k1 "default" ::k2 "default"} {::k1 2}) ;;=> {::k1 2, ::k2 "default"}

or using associative destructuring:

(let [{k1 ::k1 k2 ::k2 :or {k1 "default", k2 "default"}} 
      {::k1 2}] 
  [k1 k2]) ;; => [2 "default"]

or similarly:

(let [{:keys [::k1 ::k2] :or {k1 "default" k2 "default"}} 
      {::k1 2}] 
  [k1 k2]) ;; => [2 "default"]

Upvotes: 3

Related Questions