Can I send a mutli method for both properties of type AND to Clojure?

I have a method called visualize in my Clojure application that can supposedly display any part of my application. The problem is that some things in my application are Java classes, and some have hashmaps, and the fields that internally mark the type of map use Clojure :: idiom. I know that I can use multimaps to send by type or by some internal type, but how to do it so that the same multimethod works on BOTH.

+3
source share
1 answer

Create a submit function that looks for cards with a special marker type for Java classes as well.

(defn visualize-dispatch [foo]
  (if (map? foo) 
    (:type foo)
    (class foo)))

(defmulti visualize visualize-dispatch)

(defmethod visualize String [s] 
  (println "Got a string" s))

(defmethod visualize :banana [b] 
  (println "Got a banana that is" (:val b)))

Java {: type: banana: val "something" }.

user> (visualize "bikini")
Got a string bikini
user> (visualize {:type :banana :val "speckled"})
Got a banana that is speckled
+5

Source: https://habr.com/ru/post/1783073/


All Articles