Reputation: 15792
Why we can write
(defn factory-foo [] (fn [] (println "foo")))
(apply (factory-foo) [])
but not:
(defn factory-bar [] #((println "bar")))
(apply (factory-bar ) []) ;throws NPE
Is this a bug?
Upvotes: 0
Views: 87
Reputation: 127811
#((println "bar))
is translated by the reader to (fn [] ((println "bar")))
- note the extra parentheses. (println "bar")
here prints bar
and returns nil
, and then nil
itself is called as a function because of the outer parentheses. nil
is null
in fact, and an attempt to dereference it results to NPE.
To avoid this just drop extra pair of parentheses inside #(..)
: #(println "bar")
.
Upvotes: 7