3

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?

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

take the type hint out of the defprotocol and leave it in the extend-type

(defprotocol A
(foo [a x]))

(extend-type java.lang.String A 
  (foo [s ^Long x] (.charAt s x)))
nil
core> (foo "abracadarbra" 3)
\a

or you can change the type hint like so:

(defprotocol A
(foo [a ^Long/TYPE x]))

(extend-type java.lang.String A 
  (foo [s ^long x] (.charAt s x)))
nil
core> (foo "abracadarbra" 3)
\a

this still produces no reflection warnings without the hint in the defprotocol

EDIT:

(extend-type java.lang.String A 
  (foo [s ^Long x] (type x)))
nil
core> (foo "abracadarbra" 3)
java.lang.Long

3 Comments

thanks Arthur! this works - but is it actually using the primitive version of the function?
Hmmm not quite solving the problem then as my intention was to find a way to avoid boxing of primitive arguments.....
I may be reading that wrong, it's hard to tell because (type 4) reports the same...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.