Addendum to my previous post;

(set! *warn-on-reflection* true)
true
user=> (.compareTo myComp :d)
Reflection warning, NO_SOURCE_PATH:10 - call to compareTo can't be resolved.
1
user=> (.compareTo ^Comparable myComp :d)
1

user=> (class myComp)
user$reify__1
(instance? Comparable myComp)
true



On Wed, Sep 1, 2010 at 4:33 PM, Adrian Cuthbertson
<adrian.cuthbert...@gmail.com> wrote:
> Have a look at Stuart Halloway's video on protocols;
> http://vimeo.com/11236603
> and also clojure.core.protocols.clj in the 1.2 source code.
> A general google on clojure protocols also brings up some blogs in
> which various people have some good examples and explanations.
>
> Also note that deftype of course works for existing java interfaces as well.
>
> Reify is also useful for implementing anonymous implementations of
> java library interfaces. Here's a not very useful quick example of
> reifying the java Comparable interface;
>
> (def myComp (reify java.lang.Comparable (^int compareTo [_ k] (condp =
> k :a -1 :b 0 1))))
> #'user/myComp
> user=> (.compareTo myComp :a)
> -1
> user=> (.compareTo myComp :b)
> 0
> user=> (.compareTo myComp :c)
> 1
> user=> (.compareTo myComp :d)
> 1
>
> and another implementing and executing the java Executor interface.
>
> (import 'java.util.concurrent.Executor)
> java.util.concurrent.Executor
> user=>
> (let [f (fn[] (println "hello"))
>      thrd (reify Executor (^void execute [_ ^Runnable cmd] (.run cmd)))]
>  (.execute thrd f))
> hello
> nil
>
> These are really useful things if you do a lot of clojure/java work
> (which I do).
>
>
>
> On Wed, Sep 1, 2010 at 2:59 PM, Albert Cardona <sapri...@gmail.com> wrote:
>> Hi Adrian,
>>
>> Thanks for the explanations. Indeed I was assuming a protocol would
>> work like an interface, so I may just as well use definterface
>> directly.
>>
>> To date, protocols confuse me a bit--I have no reference for it in my
>> head. I see how you use them like multimethods and that's very neat.
>> Thanks for showing how to use them.
>>
>> It's a pity that definterface has to use "test_it" (note the
>> underscore), as you pointed out. I guess it has to do with
>> definterface having a note saying "for now, rely on gen-class" or some
>> such, in its declaration.
>>
>> Albert
>>
>> --
>> http://albert.rierol.net
>>
>> --

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