Question

How do you make a callable type or object in Clojure?

For example, how could I define a record Foo taking a single value :bar which could be called to print that value?

user=> (def foo (Foo. "Hello world"))
user=> (foo)
Hello World
user=> (:bar foo)
"Hello World"
Was it helpful?

Solution

(defrecord Foo [bar]
  clojure.lang.IFn
  (invoke [_] (println bar)))

((Foo. "Hello, world!"))

;; => Hello, world!

(:bar (Foo. "Hello, world!"))

;; => "Hello, world!"

...Whether doing this is a good idea is another question.


Records implementing IFn

(defrecord Foo [bar]
  clojure.lang.IFn
  (invoke [_] (println bar))
  (applyTo [this args] (clojure.lang.AFn/applyToHelper this args)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top