Warren Lynn <wrn.l...@gmail.com> writes:

Hi Warren,

> I found that if I define a protocol like this:
>
> (defprotocol IProc
>   (procMethod [this] "some method"))
>
> I can invoke it on a type either
> (procMethod object)
> or 
> (.procMethod object)
>
> Note the prefix dot in the second case. 
>
> I like this "dot" version because that means I can replace a record field 
> with a method with the same name and things will work as usual, like 
> "property" in Python. However, I think someone mentioned that the dot 
> version is just a JVM implementation detail that got exposed so it seems I 
> cannot rely on it as part of the language. Is that the case?

Yes.  Defining a protocol on the JVM also creates an interface with the
same name in the current package, and records and types satisfying that
protocol implement this interface.  So this works:

--8<---------------cut here---------------start------------->8---
(defprotocol Fooable
  (foo [this]))

(defrecord FooRec []
  Fooable
  (foo [this] this))

(foo (->FooRec))
#user.FooRec{}
user> (.foo (->FooRec))
Reflection warning, NO_SOURCE_FILE:1 - reference to field foo can't be resolved.
#user.FooRec{}
--8<---------------cut here---------------end--------------->8---

Note that you get a reflection warning in the dot-case which you can
avoid by type-hinting with the implicitly generated interface.

--8<---------------cut here---------------start------------->8---
user> (.foo ^user.Fooable (->FooRec))
#user.FooRec{}
--8<---------------cut here---------------end--------------->8---

However, the dot-syntax won't work if you extend your protocol
dynamically to existing types.

--8<---------------cut here---------------start------------->8---
(extend-protocol Fooable
  java.util.Date
  (foo [this] this))

user> (foo (java.util.Date.))
#inst "2012-07-23T06:07:51.130-00:00"
user> (.foo (java.util.Date.))
Reflection warning, NO_SOURCE_FILE:1 - reference to field foo can't be resolved.
No matching field found: foo for class java.util.Date
  [Thrown class java.lang.IllegalArgumentException]
--8<---------------cut here---------------end--------------->8---

Bye,
Tassilo

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