You can use a precondition (http://clojure.org/special_forms#toc9) to assert the key is present:
(defn foo [{a :keya b :keyb}]
{:pre [(not (nil? b))]}
(list a b))
This will throw an AssertionError when the key is nil.
Question
I have a function like this:
(defn foo [{a :keya b :keyb}]
(list a b))
And i'm calling it like this:
(foo {:keya "hi"}) ; Returns ("hi" nil)
If I don't give keyb
keyword argument, it takes nil for that. Is there a way to ensure that it throws exception for it instead of taking it as nil.
( I know that I can manually check and throw an exception, but is there any special option which enforces the constraints.)
Solution
You can use a precondition (http://clojure.org/special_forms#toc9) to assert the key is present:
(defn foo [{a :keya b :keyb}]
{:pre [(not (nil? b))]}
(list a b))
This will throw an AssertionError when the key is nil.
OTHER TIPS
No, but of course because Clojure is a lisp you can define your own macro that handles the boring "manual checking" for you automatically.
aldazosa gave you the right solution, but {:keya nil :keyb nil}
is the valid map too. To allow nil
values you may use contains?
instead of nil?
check:
(defn foo [{a :keya b :keyb :as m}]
{:pre [(every? (partial contains? m)
[:keya :keyb])]}
(list a b))
If you want something more complex look at Validateur or bouncer