On Nov 21, 12:24 pm, Sean Corfield <seancorfi...@gmail.com> wrote:
> On Mon, Nov 21, 2011 at 8:12 AM, Tassilo Horn <tass...@member.fsf.org> wrote:
> > But is that really an issue?  I mean, since you cannot use such duck
> > typing in Java itself (except in terms of reflection), any method
> > defined for more than one class with shared, consistent semantics is
> > declared in some common parent class or interface which you can use for
> > your type hint.
>
> There are cases, in several contrib libraries, where a single function
> effectively wraps a set of overloaded Java methods. In order to add
> type hints in such situations, the code would have to expand to a
> series of conditionals that queried the type at runtime just so
> different branches could type hint the overloaded calls correctly (to
> remove the warnings). I don't think that's a good idea.

This is way, way faster than using reflection. And all you need in
order to remove the duplication is a macro that does the hinting for
you:

(defmacro multi-hinted-let [[name expr classes] & body]
  (let [x (gensym)]
    `(let [~x ~expr]
       (condp instance? ~x
         ~@(for [class classes
                 clause [class `(let [~(with-meta name {:tag class})
~x] ~@body)]]
             clause)
         (throw (IllegalArgumentException. (str "No matching class for
" ~x " in " '~classes)))))))

(def l (ArrayList.))


user> (.size l)
Reflection warning, NO_SOURCE_FILE:1 - reference to field size can't
be resolved.
0

user> (multi-hinted-let [x l [LinkedList ArrayList]] (.size x))
0


user> (macroexpand-1 '(multi-hinted-let [x l [LinkedList ArrayList]]
(.size x)))

(let [G__2251 l]
  (condp instance? G__2251
    LinkedList (let [^LinkedList x G__2251] (.size x))
    ArrayList  (let [^ArrayList x G__2251] (.size x))
    (throw (IllegalArgumentException. (str "No matching class for "
G__2251 " in " (quote [LinkedList ArrayList]))))))

-- 
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