8

I want my program act differently between primitive types and their wrapper classes, for example:

(defmulti try-type class)

(defmethod try-type Integer [arg]
  (println "Integer"))

(defmethod try-type Integer/TYPE [arg]
  (println "int"))

But it doesn't work, though i try Integer and int both

user=> (try-type (.intValue (int 2)))
Integer
nil
user=> (try-type  (int 2))
Integer
nil

So, is it possible to dispatch multimethod on primitive types?

======EDIT======

i was wrapping a google guava into clojure. There is a primitive library in it, such as Booleans, Dobules, Ints etc. They have some methods in common, so i want to try multimethod.

qiuxiafei
  • 5,827
  • 5
  • 30
  • 43
  • could you explain why you want to do this? currently dispatching on primitives is not possible, but there is probably a good way to achieve the same objective (google "XY Problem") – mikera Jul 30 '12 at 00:46

1 Answers1

4

No, it is not currently possible. An arg to a function (such as the multimethod dispatch function) is either an Object (thus primitives will be boxed) or a primitive long/double (thus Objects will be unboxed). Your scenario requires a function that can take either and preserve that distinction inside the function.

That said, there may be solutions to whatever is the actual problem you're trying to solve.

Alex Taggart
  • 7,805
  • 28
  • 31