Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what advantage is there to use 'get' instead to access a map

Tags:

clojure

Following up from this question: Idiomatic clojure map lookup by keyword

Map access using clojure can be done in many ways.

(def m {:a 1}

(get m :a) ;; => 1
(:a m) ;; => 1
(m :a) ;; => 1

I know I use mainly the second form, and sometimes the third, rarely the first. what are the advantages (speed/composability) of using each?

like image 206
zcaudate Avatar asked Jan 23 '13 20:01

zcaudate


1 Answers

get is useful when the map could be nil or not-a-map, and the key could be something non-callable (i.e. not a keyword)

(def m nil)
(def k "some-key")

(m k)  =>  NullPointerException
(k m)  =>  ClassCastException java.lang.String cannot be cast to clojure.lang.IFn

(get m k)  =>  nil
(get m :foo :default)  =>  :default
like image 142
Chris Perkins Avatar answered Nov 03 '22 14:11

Chris Perkins