How to reuse deftype methods in Clojure / Clojurescript?

I am trying to expand the DomKM / silk library.

In particular, there is a deftype Route that implements the Pattern protocol, which has implementation methods that I would like to use in my custom implementation of the Pattern protocol.

https://github.com/DomKM/silk/blob/master/src/domkm/silk.cljx#L355

 (deftype Route [name pattern] Pattern (-match [this -url] (when-let [params (match pattern (url -url))] (assoc params ::name name ::pattern pattern))) (-unmatch [this params] (->> (dissoc params ::name ::pattern) (unmatch pattern) url)) (-match-validator [_] map?) (-unmatch-validators [_] {})) 

Ok, so my implementation would look like this, but I would like to inherit Route methods. I mean, to execute some user logic first, and then pass it to the original Route methods.

 (deftype MyRoute [name pattern] silk/Pattern (-match [this -url] true) ;match logic here (-unmatch [this {nm ::name :as params}] true) ;unmatch logic here (-match-validator [_] map?) (-unmatch-validators [_] {})) 

How is this done in clojure / clojurescript?

+5
source share
1 answer

There is no need to override the type. Referring to the implementation of the ancestor protocol, perhaps from a different namespace.

 user=> (ns ns1) nil ns1=> (defprotocol P (f [o])) P ns1=> (deftype T [] P (f [_] 1)) ns1.T ns1=> (f (T.)) 1 ns1=> (ns ns2) nil ns2=> (defprotocol P (f [o])) P ns2=> (extend-protocol P ns1.T (f [o] (+ 1 (ns1/fo)))) nil ns2=> (f (ns1.T.)) 2 

Keep in mind that ns1.P and ns2.P are completely different cats, both called P

+1
source

All Articles