2012-01-16 259 views
2
core=> (defrecord Puffball [id name]) 
core.Puffball 
core=> (Puffball. 149 "Urist") 
#core.Puffball{:id 149, :name "Urist"} 
core=> (apply Puffball. [149 "Urist"]) 
CompilerException java.lang.RuntimeException: java.lang.ClassNotFoundException: Puffball., compiling:(NO_SOURCE_PATH:3) 
core=> (apply Puffball [149 "Urist"]) 
ClassCastException java.lang.Class cannot be cast to clojure.lang.IFn clojure.core/apply (core.clj:600) 

如何從矢量創建馬勃球?調用適用於defrecord構造函數?

回答

8

在Clojure中1.3記錄定義自動地引入工廠功能:

Clojure 1.3.0 
user=> (defrecord Puffball [id name]) 
user.Puffball 
user=> (apply ->Puffball [149 "Urist"]) 
#user.Puffball{:id 149, :name "Urist"} 

->Puffball是 「位置」 工​​廠功能;也有map->Puffball這是顧名思義。

0

對於那些不上的1.3.x(或需要的記錄以外這樣的功能),下面模擬apply用java方法和構造:

 
(defmacro applyj 
    ([mc args] `(~mc [email protected])) 
    ([mc x args] `(~mc ~x [email protected])) 
    ([mc x y args] `(~mc ~x ~y [email protected])) 
    ([mc x y z args] `(~mc ~x ~y ~z [email protected]))) 
 
user=> (defrecord Puffball [id name]) 
user.Puffball 
user=> (applyj Puffball. [149 "Urist"]) 
#:user.Puffball{:id 149, :name "Urist"}