Keywords and Symbols
Prerequisites: Strings and characters
Keywords
A keyword starts with a colon: :name, :status, :http/get.
Keywords evaluate to themselves and are used everywhere as map keys and
as named constants.
(def user {:name "Ada" :role :admin})
(println (:name user)) ; a keyword is a function that looks itself up
(println (:email user)) ; missing key: nil
(println (:email user "none")) ; with a default
(println (= :admin (:role user)))
(println (keyword "status") (name :status))
(println :shop/order (namespace :shop/order))
Ada
nil
none
true
:status status
:shop/order shop
(:key map)reads a value — the most common way to access maps.- Keywords compare very fast, so they're ideal for statuses and
options (
:pending,:done). - Qualified keywords like
:shop/orderinclude a namespace, which avoids clashes between libraries.::ordermeans "qualified with the current namespace".
Symbols
A symbol is a name that refers to something — println, user,
str/join. When evaluated, a symbol is replaced by its value. Quote it
to use the symbol itself as data:
(def answer 42)
(println answer) ; the value
(println 'answer) ; the symbol
(println (type 'answer) (type :answer))
(println (symbol "x") (resolve 'println))
42
answer
clojure.lang.Symbol clojure.lang.Keyword
x #'clojure.core/println
You rarely work with symbols directly until you write macros (Level 3); for data, use keywords.