Search code examples
dictionaryclojureclojure-java-interop

How to distinguish java map from clojure map?


Let's say I have the following code:

(def m1 (java.util.HashMap.))
(def m2 (java.util.LinkedHashMap.))
(def m3 {})

I need a function that will allow me to detect maps that came from java, e.g.:

(map java-map? [m1 m2 m3]) ;; => (true true false)

Anything out of the box?


Solution

  • i would do this:

    user=> (defn java-map? [m] 
             (and (instance? java.util.Map m) 
                  (not (map? m))))
    #'user/java-map?
    
    user=> (java-map? {})
    false
    
    user=> (java-map? (java.util.HashMap.))
    true
    
    user=> (java-map? [])
    false
    

    so you just check that it implements core java's Map interface, but not being a clojure's persistent map.