简体   繁体   中英

Clojurescript defprotocol and defrecord in different namespaces

This works fine:

(ns ns1) 
(defprotocol P
  (foo [this a]))

(defrecord Foo [attr]
  P
  (foo [this a] a))

(println (foo (Foo. "test") "Works!"))

But when I move the protocol to its own namespace like so:

(ns ns2) 
(defprotocol P
  (foo [this a]))

Then this throws a Use of undeclared var ns1/foo

(ns ns1
  (:require ns2 :refer [P]))

(defrecord Foo [attr]
  P
  (foo [this a] a))

(println (foo (Foo. "test") "Undeclared var?"))

I found this really nice write up that makes sense for Clojure and Java.

Is it possible to get my example above to work in clojurescript?

Update: I knew I was missing something super simple! For the record, as mentioned in the accepted answer: all I needed was to refer foo like so:

(ns ns1
  (:require ns2 :refer [P foo]))

(defrecord Foo [attr]
  P
  (foo [this a] a))

(println (foo (Foo. "test") "Works once again"))

The answer is right in the blog post you linked. You have to :refer the protocol functions you wish to use (or use them more explicitly, as is the style these days, using :require :as ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM