简体   繁体   中英

Why does this anonymous function starting with println result in a NullPointerException?

I am learning about pmap and wrote the following function:

(pmap #((println "hello from " (-> (Thread/currentThread) .getName)) 
         (+ %1 %2)) 
   [1 1 1] [-1 -1 -1])

When run, the result is a NullPointerException

(hello from  clojure-agent-send-off-pool-4
hello from  clojure-agent-send-off-pool-3
hello from  clojure-agent-send-off-pool-5
NullPointerException   user/eval55/fn--56 (NO_SOURCE_FILE:11)

Why is this happening? I have understood and observed the body of a fn to be an implicit do .

匿名fn文字#()没有隐式do

You have println in 2 parens so the result of println is evaluated. println always returns nil hence the NullPointerException.

Try removing the extra parens from the #() :

   (pmap #(println "hello from " 
         (-> (Thread/currentThread) .getName) 
         (+ %1 %2)) 
          [1 1 1] [-1 -1 -1] )

EDIT:

Then you will need the do as mentioned in other comments like:

(pmap #(do (println "hello from " 
     (-> (Thread/currentThread) .getName)) 
     (+ %1 %2)) 
      [1 1 1] [-1 -1 -1] )

The reason the do is necessary in the #() reader macro is not that functions don't include an implicit do but has to do with the way the macro expands. Basically, that macro assumes a single form hence the need for the explicit do .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM