...
user> (defmulti mm type)
#'user/mm
user> (type "a")
java.lang.String
user> (defmethod mm java.lang.String [s] (println "string"))
#<MultiFn clojure.lang.MultiFn@41e3a0ec>
user> (mm "a")
string
nil
user> (type (.getBytes "a"))
[B
user> (defmethod mm [B [b] (println "bytes"))
; Evaluation aborted.
user> (def ba-type (type (.getBytes "a")))
#'user/ba-type
user> (defmethod mm ba-type [b] (println "bytes"))
#<MultiFn clojure.lang.MultiFn@41e3a0ec>
user> (mm (.getBytes "a"))
bytes
nil
user>
...
It works easily for the string, but for a native java byte array, type (or class) gives me back this "[B", which I'm unable to use as a dispatch value for the defmethod.
I can, however, assign the value to a reference and us that to dispatch on successfully - but that feels like a hack.
Is there a way to express the byte array type in a different way than "[B" that would work?
Thanks, Frank.
On Mar 24, 11:02 am, Frank Siebenlist <frank.siebenl...@gmail.com>
wrote:
-FS.
> --
> You received this message because you are subscribed to the Google
> Groups "Clojure" group.
> To post to this group, send email to clo...@googlegroups.com
> Note that posts from new members are moderated - please be patient with your first post.
> To unsubscribe from this group, send email to
> clojure+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/clojure?hl=en
>
> To unsubscribe from this group, send email to clojure+unsubscribegooglegroups.com or reply to this email with the words "REMOVE ME" as the subject.
But since the clojure way to obtain a class is simply to use its name
literal, e.g.:
user=> (type String)
java.lang.Class
the only way to get the class of an array would involve either a
function call or a change to the reader. And java doesn't make it
easy since all array-class stuff, such as Class.isArray(), is native
code. The best I've come up with is:
user=>
(defn #^Class array-class
"Returns the Class of an array of component type c"
[#^Class c]
(when c (class (java.lang.reflect.Array/newInstance c 0))))
user=> (array-class String)
[Ljava.lang.String;
which appears faster than using Class/forName with a created string.
But since one *can* type a literal byte array class in java, I'd
imagine there's some way to implement this with bytecode magic, rather
than going through java.lang.reflect.Array.
On Mar 24, 3:39 pm, Frank Siebenlist <frank.siebenl...@gmail.com>
wrote:
Your code can work this way:
user=> (defmethod mm (resolve (symbol "[B")) [b] (println "bytes"))
#<MultiFn clojure.lang.MultiFn@6ee3849c>
user=> (mm (.getBytes "a"))
bytes
nil
In the end though, it turns out to be just another way to call (Class/
forName "[B").
-Frank.
On Mar 24, 7:49 pm, Frank Siebenlist <frank.siebenl...@gmail.com>