Importing defprotocol and deftype

2,357 views
Skip to first unread message

Shantanu Kumar

unread,
Feb 5, 2011, 2:20:02 PM2/5/11
to Clojure
When I declare using defprotocol:

(defprotocol IFoo
(bar [this] "some doc"))

and then using deftype:

(deftype Foo
IFoo
(bar [this] "from Foo::bar"))

I noticed there is an interesting difference in the way I need to
import them in another namespace:

(:import
(com.example_ns IFoo) ; importing Foo here gives error (notice
underscore)
(com.example-ns Foo)) ; importing IFoo here gives error (notice
dash)

Can somebody explain the rationale behind this? The dash character is
not valid inside a Java package names so a protocol not supporting it
is understandable. But when I deftype something, is it not supposed to
be consumed from within Java-the-language?

Shantanu

trptcolin

unread,
Feb 6, 2011, 3:59:34 PM2/6/11
to Clojure
Forgive me if I'm misunderstanding, but you don't need to import a
protocol to use it. If you need to actually get ahold of the protocol
(say, to implement another deftype/defrecord), you can just use
`require` or `use` to get ahold of it:

(ns stuff
(:use [com.example-ns :only [IFoo])
(:import [com.example-ns Foo]))

Then inside that ns, you can just refer to IFoo and Foo. I'm
surprised that the underscored version of the import works for a
protocol - I've never seen anyone use that before. I wonder if it's
just an oversight on my part or if that's a non-recommended use of
import...

Micah Martin just showed me a behavior very similar to this recently,
and since then I'd been thinking of protocols more like normal Clojure
data structures, and deftypes/defrecords more like Java classes.
Confirming that, if I look at the type of IFoo, it is a
clojure.lang.PersistentArrayMap, and Foo is a java.lang.class.

Colin

Stuart Sierra

unread,
Feb 8, 2011, 4:45:42 PM2/8/11
to clo...@googlegroups.com
`defprotocol` creates a real Var, which you can `use` or `refer` just like a function.

`deftype` and `defrecord` both create classes, which you must `import` using the class name.  Class names have to be compatible with Java, so dashes are converted to underscores.

-Stuart Sierra

Reply all
Reply to author
Forward
0 new messages