Search code examples
javaclojureclojure-java-interop

Get unknown key from Clojure Persistent Hash


What is the best way to get an unknown key from a Clojure map? I tried this -

(key {:a "test"})

which throws this -

ClassCastException clojure.lang.PersistenArrayMap cannot be cast to java.util.Map$Entry

Looking at the source code, this makes sense-

(defn key
  "Returns the key of the map entry."
  {:added "1.0" :static true}
  [^java.util.Map$Entry e]
  (. e (getKey)))

I also tried this-

(key (java.util.Map$Entry. {:a "test"}))

Which throws this-

CompilerException java.lang.IllegalArgumentException: No matching ctor found for interface java.util.Map$Entry

I understand that I can call keys and then pull said key from the KeySeq, but I was curious if there is a simple way to do this with one function call.

This is a related question in terms of interop. Thanks for the input.


Solution

  • (key (first {:a "test"})) will get you the key of the first entry in the map, is that what you are trying to do?