Improve support for extending protocols to primitive arrays


  • Type: Enhancement Enhancement
  • Status: Open Open
  • Priority: Major Major
  • Resolution: Unresolved
  • Affects Version/s: Release 1.5, Release 1.6
  • Fix Version/s: None
  • Component/s: None
  • Labels:
  • Approval:


It is possible to extend protocols to primitive arrays but specifying the class for the type is a little tricky:

(defprotocol P (p [_]))
(extend-protocol P (Class/forName "[B") (p [_] "bytes"))
(p (byte-array 0))   ;; => "bytes"

However, things go bad if you try to do more than one of these:

(extend-protocol P 
  (Class/forName "[B") (p [_] "bytes")
  (Class/forName "[I") (p [_] "ints"))
CompilerException java.lang.UnsupportedOperationException: nth not supported on this type: Character, compiling:(NO_SOURCE_PATH:1:1)
	clojure.lang.Compiler.analyze (
	clojure.lang.Compiler.analyze (
	clojure.lang.Compiler$MapExpr.parse (
	clojure.lang.Compiler.analyze (
	clojure.lang.Compiler.analyze (
	clojure.lang.Compiler$InvokeExpr.parse (
	clojure.lang.Compiler.analyzeSeq (
	clojure.lang.Compiler.analyze (
	clojure.lang.Compiler.analyze (
	clojure.lang.Compiler$BodyExpr$Parser.parse (
	clojure.lang.Compiler$FnMethod.parse (
	clojure.lang.Compiler$FnExpr.parse (
Caused by:
UnsupportedOperationException nth not supported on this type: Character
	clojure.lang.RT.nthFrom (
	clojure.lang.RT.nth (
	clojure.core/emit-hinted-impl/hint--5951/fn--5953 (core_deftype.clj:758)
	clojure.core/map/fn--4207 (core.clj:2487)
	clojure.lang.LazySeq.sval (
	clojure.lang.LazySeq.seq (
	clojure.lang.RT.seq (
	clojure.lang.RT.countFrom (
	clojure.lang.RT.count (
	clojure.lang.Cons.count (
	clojure.lang.Compiler.analyze (
	clojure.lang.Compiler.analyze (

The code in {parse-impls} is seeing the second {(Class/forName "[I")} as a function, not as a new type. One workaround for this is to only extend the protocol to one type at a time.

It would be even better (moving into enhancement area) if there was a syntax here to specify primitive array types - we already have the syntax of {bytes, ints, longs}, etc for type hints and those seem perfectly good to me.



Vote (4)
Watch (3)


  • Created: