Stan Kurilin
Stan Kurilin

Reputation: 15792

Higher-order functions and short forms

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

Answers (1)

Vladimir Matveev
Vladimir Matveev

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

Related Questions