Search code examples
clojureprotocolsprimitive

Using a protocol with primitive arguments


I'm trying to define a protocol in Clojure 1.4 with primitive arguments (so that I can avoid unnecessary primitive boxing in performance-sensitive code):

(defprotocol A
  (foo [a ^long x]))

(extend-type java.lang.String A 
  (foo [s ^long x] (.charAt s x)))

This look like it works OK but fails with an exception when I try to use it:

(foo "abracadarbra" 3)
=> ClassCastException XXXX cannot be cast to clojure.lang.IFn$OLO

What am I doing wrong?


Solution

  • After some further reasearch it appears that protocols do not yet support primitive type hints (as of Clojure 1.4). See e.g. https://groups.google.com/d/topic/clojure-dev/HxBqIewc494/discussion

    Alternatives seem to be:

    • Write regular functions with primitive hints. You lose polymorphism.
    • Use a Java interface (you can use reify to build instances in Clojure)