Clojure: working with a java.util.HashMap in an idiomatic Clojure fashion

后端 未结 4 1475
醉酒成梦
醉酒成梦 2020-12-14 07:12

I have a java.util.HashMap object m (a return value from a call to Java code) and I\'d like to get a new map with an additional key-value pair.

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-14 07:30

    It's totally OK to use the java hash map in the traditional way.
    (do (. m put "key" "value") m)
    This is not idiomatic Clojure code, plus I'm modifying m instead of creating a new map.

    You are modifying a data structure that really is intended to be modified. Java's hash map lacks the structural sharing that allows Clojures map's to be efficiently copied. The generally idiomatic way of doing this is to use java-interop functions to work with the java structures in the typical java way, or to cleanly convert them into Clojure structures and work with them in the functional Clojure way. Unless of course it makes life easier and results in better code; then all bets are off.

提交回复
热议问题