Reputation: 9749
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)
How can I create puffballs from vectors?
Upvotes: 2
Views: 595
Reputation: 7825
For those not on 1.3.x (or need such functionality outside of records), the following simulates apply
with java methods and constructors:
(defmacro applyj ([mc args] `(~mc ~@args)) ([mc x args] `(~mc ~x ~@args)) ([mc x y args] `(~mc ~x ~y ~@args)) ([mc x y z args] `(~mc ~x ~y ~z ~@args)))
user=> (defrecord Puffball [id name]) user.Puffball user=> (applyj Puffball. [149 "Urist"]) #:user.Puffball{:id 149, :name "Urist"}
Upvotes: 0
Reputation: 84341
In Clojure 1.3 record definitions automagically introduce factory functions:
Clojure 1.3.0
user=> (defrecord Puffball [id name])
user.Puffball
user=> (apply ->Puffball [149 "Urist"])
#user.Puffball{:id 149, :name "Urist"}
->Puffball
is the "positional" factory function; there's also map->Puffball
which does what its name suggests.
Upvotes: 8