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"
(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)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With