Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

Why can't I extend Clojure's IFn using extend-type?

I saw David Nolen's talk on ClojureScript where he makes extends IFn to Regexp and so that we can call a regex literal as a fuinction on a string to check for matches.

I tried something similar with Strings in regular Clojure, but I get this exception. I see that IFn is an interface written in Java but how does the implementation work in CLojrue front.

(extend-type java.lang.String
  #_=>    clojure.lang.IFn
  #_=>   (-invoke
  #_=>    ([this index]
  #_=>     (get (seq this) index))))
IllegalArgumentException interface clojure.lang.IFn is not a protocol  clojure.core/extend (core_deftype.clj:742)

Upvotes: 8

Views: 987

Answers (1)

Diego Basch
Diego Basch

Reputation: 13079

The exception should give you a hint. IFn is not a protocol in Clojure. It is in ClojureScript. You can extend protocols, implement Java interfaces, and subclass classes. In this particular case, you cannot even subclass java.lang.String because it's declared final.

Upvotes: 9

Related Questions