I'm coming from a heavy javascript background and learning clojure.
In js we can do;
var aVariable; //evaluates as falsy
var x = aVariable || 'my Default String';
How do you do this in clojure?
Currently I'm reading a header out of a request map coming from compojure.
(let [x-forwarded-for (get-in request [:headers "x-forwarded-for"])]
(println x-forwarded-for)
)
In the case where the 'x-forwarded-for' header doesn't exist, the x-forwarded-for value is nil. What's the proper way to test for nil and then reassign x-forwarded-for to another value?
You can use the built-in or
:
(let [x-forwarded-for (or (get-in request [:headers "x-forwarded-for"]) "my Default String")]
(println x-forwarded-for))
If the first clause is nil
, it will use the second.
Luckily the get-in
function has a not-found
parameter for exactly this use case:
(let [x-forwarded-for (get-in request [:headers "x-forwarded-for"]
"default value")]
(println x-forwarded-for))
In general, you could use or
as @prismofeverything said.
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