Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dispatch multimethod on primitive types?

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.

like image 465
qiuxiafei Avatar asked Jul 28 '12 16:07

qiuxiafei


1 Answers

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.

like image 52
Alex Taggart Avatar answered Oct 20 '22 11:10

Alex Taggart