I'm kind of new to Clojure at the moment, and have been playing around
re-writing some utility libraries from work in Clojure for import into
other pieces of our infrastructure. I'm having a blast using it, but I've
gotten a bit stuck on trying to implement something with Multimethods. I
have a multimethod dispatching based upon class – for example:
(ns interop.core
> (:gen-class
> :methods [[doSomething [String] String]
> [doSomething [Integer] Integer]
> [doSomething [Object] String]]))
> (defmulti -doSomething (fn [this valueHolder & default] (class
> valueHolder)))
> (defmethod -doSomething String [this valueHolder]
> (if (nil? valueHolder) "a" "b"))
> (defmethod -doSomething Integer [this valueHolder]
> (if (nil? valueHolder) (Integer. 1) (Integer. 2)))
> (defmethod -doSomething :default [this valueHolder]
> (if (nil? valueHolder) "c" "d"))
If I compile and export this, and attempt to use it in a Java project, it
works fine for most use cases:
core c = new core();
> System.out.println(c.doSomething(new Integer(1))); // 2 --> Correct
> System.out.println(c.doSomething("")); // 'b' --> Correct
> System.out.println(c.doSomething(new Object())); // 'd' --> Correct
> // System.out.println(c.doSomething(null)); // The method
> doSomething(String) is ambiguous
> System.out.println(c.doSomething((String) null)); // 'd' --> Wrong
> System.out.println(c.doSomething((Object) null)); // 'd' --> Correct
> System.out.println(c.doSomething((Integer) null)); // ClassCastExc: String
> cannot be cast to Integer
The oddity is the last line. It looks like it's: Calling the Object =>
String implementation (marked default), but its trying to cast the result
after the fact to an Integer (to match the Integer => Integer
implementation). If I had to make a guess, I'd say the return type is being
correctly matched, but the input parameter is causing the :default
implementation to always be called. Anyone have any suggestions or ideas on
either what I'm doing wrong, or even just whats happening behind the
scenes? Any ideas on how to fix whats probably an egregious mistake on my
behalf?
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en