On May 9, 9:50 am, Chris Perkins <chrisperkin...@gmail.com> wrote:
> On May 9, 8:00 am, Simon Katz <nomisk...@gmail.com> wrote:
> > I'm trying to implement a function similar to new, but where
> > the type is not known at compile time -- so I want to evaluate
> > the first argument.
>
> > With the help of Google, I found the approach used in new*
> > below:
>
> >     (ns dynamic-new)
>
> >     (defn new* [type-name-as-symbol & args]
> >       (clojure.lang.Reflector/invokeConstructor
> >        (resolve type-name-as-symbol)
> >        (to-array args)))
> > Now my questions:
>
> > Q1. Is this basically the right approach, or is there some other
> >     way to implement new*?
>
> Is there a reason that you need to pass a symbol, rather than the
> Class object itself?  eg:
>
> (defrecord Foo [a b])
>
> (defn new* [klass & args]
>   (clojure.lang.Reflector/invokeConstructor klass (to-array args)))
>
> (new* Foo 23 "hello")
> #:user.Foo{:a 23, :b "hello"}
>
> - Chris Perkins

A mild gripe: we're in a language that doesn't make us use ugly names
like klass and clazz. Some will disagree with me for sure, but I think
it's more readable to simply use the symbol "class" when you're
talking about a class. If you disagree, by all means continue to use
klass; I'm just trying to prevent someone sticking with old java
habits because they don't realize they have a choice.

As to the content: yes, passing a class (which will get resolved in
the right namespace) is much much easier than passing a symbol and
then trying to resolve it "by magic".

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to