Clojure way to get a value of a non-keyword key in map

HI all,

I know that the Clojure proper style to get value from

(def my-map {:my 100 :large 200 :map 300})

is

(:my my-map)

But what about maps with non-keyword keys?

Should I use

(def my-map {"my" 100 "large" 200 "map" 300})
(my-map "large")

or

(get my-map "large")

I know I need to use (get ... if I want to specify a default value (get my-map "large" :not-found) but except that, it’s the same as (map key}

Could anyone please tell me what do cool kids use for this?

Thank you,

Ralf

I tend to name maps I tend to use as functions like something->something-else

After testing in REPL, TIL than we can use default fallback without get too:

(my-map "large" :not-found)
1 Like

That’s a good tip ;-).

Thx!

I think no get is the way to go :wink:

1 Like

I’ll use get when the map could potentially be nil. A nil in the function position will throw a NullPointerException.

1 Like

I almost always use (get my-map "key") for fear of my-map being nil.

1 Like

It turns out keyword access also works for symbols;

user> ('x '{x 2})
2

I didn’t know that years back and ended up with a subtle bug since I almost never do this.

Fyi, using the map-as-function form ({:x 2} :x) has the side benefit of being typically faster than going through the polymorphic clojure.core/get (and surprisingly faster than the keyword access route without much change), since get works on java maps and sets and arrays. All the polymorphism adds overhead per access.

4 Likes

I like to use get to make it clear to the reader it is a map, possibly with a default value.

I also like to use the function grab from Tupelo Clojure as it will throw an exception if the key is not present.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.