How to dispatch multimethod on primitive types?
Asked Answered
G

1

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.

Garrison answered 28/7, 2012 at 16:47 Comment(1)
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")Amadou
A
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.

Avens answered 28/7, 2012 at 18:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.