Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a callable object in Clojure?

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"
like image 562
Jeremy Avatar asked Dec 05 '10 11:12

Jeremy


1 Answers

(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)))
like image 146
MayDaniel Avatar answered Nov 17 '22 04:11

MayDaniel