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.)
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.
No, but of course because Clojure is a lisp you can define your own macro that handles the boring "manual checking" for you automatically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With