Why does the following Clojure program throw a NullPointerException?
user=> (defn x []
"Do two things if the expression is true."
(if true ((println "first expr") (println "second expr")) false))
user=> (x)
first expr
java.lang.NullPointerException (NO_SOURCE_FILE:0)
second expr
This is a simplified version of my actual use case, where I want to execute maybe three statements (pull values from the DB) before returning a map - {:status 200, :body "Hello World"}
inside of the branch.
It is trying to treat the result of the first println as a function to call on the second println function.
You need a do
.
(defn x []
"Do two things if the expression is true."
(if true (do (println "first expr") (println "second expr")) false))
(x)
The do
special form (progn in CL, begin in Scheme) executes each of its arguments in sequence and returns the result of the last one.
If nil
is ok as a return value in the else case, consider using when
which has an implicit do
block:
(defn x []
"Do two things if the expression is true."
(when true
(println "first expr")
(println "second expr")))
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