Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 478
OlegTheCat Avatar asked Dec 14 '22 07:12

OlegTheCat


1 Answers

You can use map? to check if something implements IPersistentMap which is true for Clojure maps but not for java.utils.* maps:

(map? (java.util.HashMap.)) ;; => false
(map? (java.util.LinkedHashMap.)) ;; => false
(map? {}) ;; => true

To be more precise you should rather check if a given object meets some requirements (e.g. is persistent, immutable/mutable - map? will answer that specific question). There is no easy way to tell if you got a Java implementation of a map as you could get any other implementation from external library which might have a custom implementation of java.util.Map or extending one of the concrete implementations from java.util package.

like image 93
Piotrek Bzdyl Avatar answered Jan 01 '23 20:01

Piotrek Bzdyl