Welcome! Please see the About page for a little more info on how this works.

0 votes
in Clojure by

I learned about keywords a while back, but Im not sure what they are actually used for outside of for keys in maps. Are there other uses for keywords outside of maps?

Also what do they actually mean and do?

2 Answers

+3 votes
by

Keywords and symbols are both good for naming things. Symbols evaluate to the thing they refer to, so are typically used for functions. Keywords evaluate to themselves so they make good attribute names or enumerated values.

Some other benefits of keywords over symbols as names is that they are interned (only one instance of a particular keyword is reused across the runtime, so 1000 maps with the same attribute use only one keyword in memory), and they also have a fast (identity) implementation of equality.

+1 vote
by

They're a data type for names, suppose I gave you this JSON:

{
  "a" : "b",
  "c": {
    "d": "e"
  }
}

It's impossible to tell what is a name and what is a value

Keywords give you the ability to show what is a label

Keywords can also be used as lookup functions like

(-> data :person :address :house-number) ;; 5
...