Johan
Johan

Reputation: 40500

Extend protocol defined in another namespace in Clojure?

I have this protocol defined in namespace x:

(ns x
  (:require [..]))

(defrecord MyData [something something-else])


(defprotocol MyProtocol
  (my-fn [data]))

Now I want to create an implementation of this protocol in another namespace. I've tried doing something like this:

(ns y
  (:require [..])
  (:import (x MyData MyProtocol)))

(extend-protocol MyProtocol
  MyData
  (my-fn [data]
    ; Do something with the data
    ))

However when I try to execute my-fn like this (from my test case):

(ns y-test
  (:require [x :refer [MyData my-fn]]
            [...]))

...

(let [data (->MyData ...)]
    (my-fn data))

I get the following exception:

java.lang.IllegalArgumentException: No implementation of method: :my-fn of protocol: #'x/MyProtocol found for class: x.MyData

If I move MyProtocol to namespace y it seem to work. What am I missing?

Update

After ayato_p's answer I required the Protocol (in y) instead of importing it but I still get the same error. Moving extend-protocol from y to x resolves the problem.

Upvotes: 4

Views: 790

Answers (1)

ayato_p
ayato_p

Reputation: 433

import is just for Java classes, so you can't import MyProtocol by :import.

Following code works with your record type and protocol.

(ns y
  (:require [.. Myprotocol])
  (:import (x MyData)))

Upvotes: 2

Related Questions