开发者

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"


(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)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜