Emmanuel Touzery
Emmanuel Touzery

Reputation: 9173

shortcut to define parameterless functions in clojure

I am searching for a shortcut to define parameterless functions in clojure:

=> (def x (fn [] (println "test")))
#'x
=> (x)
test
nil
=> (def y (println "test"))
test
#'y
=> (y)
NullPointerException   core/eval2015 (form-init5842739937514010350.clj:1)

I would really like to avoid typing the fn []. I know about the lambda notation #() but it requires at least one parameter. I would use them in a GUI binding to handle button click events where I don't care about the event itself, I just need to know the button was clicked.

Upvotes: 0

Views: 165

Answers (2)

Diego Basch
Diego Basch

Reputation: 13079

In addition to noisesmith's response (which is the right answer to the question), in this particular case you could also do:

(def y (partial println "test"))

which would print test when called as (y), or test hello when called as (y "hello").

Upvotes: 2

noisesmith
noisesmith

Reputation: 20194

user> (def y #(println "test"))
#'user/y
user> (y)
test

Upvotes: 3

Related Questions