开发者

Run two commands in a row after an if statement in Clojure

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")))


Not that it matters in your particular case, but do know the difference between (do ...) which will load each form in its own classloader, and an empty let form (let [] ...) which evaluates the whole form in a single classloader.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜