How to dispatch multimethod on primitive types?

298 views Asked by At

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.

1

There are 1 answers

0
Alex Taggart On

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.