Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 512
mikera Avatar asked Jan 29 '26 15:01

mikera


1 Answers

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)
like image 67
mikera Avatar answered Feb 03 '26 06:02

mikera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!