与地图不同,记录不是功能.为什么?
;; maps are functions of the keys
({:a 1} :a) ;; 1
({:a 1}) ;; error
({:a 1} 1) ;; nil
;; records? no, records are not functions
(defrecord T [t])
((->T 1) :t) ;; error: T cannot be cast to clojure.lang.IFn
(:t (->T 1)) ;; 1
Run Code Online (Sandbox Code Playgroud)
其他人已经回答了这个问题,但是这里是你如何使你的一个defrecord类型实现IFn接口:
user> (defrecord Blah
[x y]
clojure.lang.IFn
(invoke [o arg] (arg o)))
user> (let [obj (->Blah 1 2)]
[(obj :x) (obj :y)])
[1 2]
Run Code Online (Sandbox Code Playgroud)