Elixir Atoms and its different forms

Viewed 104

So, as a newbie to Elixir lang, I am thoroughly confused with : (colons) on both sides of a variable!

:status is an atom, but we also find in maps or structs stuff like so:

%{
   kkey: "success"
 }

Is the kkey an atom? If so, how is this different from :kkey, the standard way of declaring an atom!

Another example to drive home the point:

IO.inspect(some_variable, label: "value of some_variable")

In this example, is label: considered an atom?

Furthermore, in Keyword List are all keys atoms?

Appreciate clarifications. Thanks!

2 Answers

Your assumptions are correct:

%{
  kkey: "success"
}

is equivalent to:

%{
 :kkey => "success"
}

For more information about Keyword lists, read the documentation.

The answer from zwippie is correct. I want to add one little thing. You mentioned IO.inspect, e.g.

IO.inspect(some_variable, label: "value of some_variable")

and you are correct to assume that label: is an atom, but in this case it is a Keyword list as the second argument. The following lines are all equivalent:

IO.inspect(some_variable, label: "value of some_variable")
IO.inspect(some_variable, [label: "value of some_variable"])
IO.inspect(some_variable, [{:label, "value of some_variable"}])

So a Keyword list in Elixir which looks like

[a: 1, b: "yes"]

is actually shorthand for a "list of 2-tuples":

[{:a, 1}, {:b, "yes"}]

Many times the options argument in a function is a Keyword list like this and if you know about the "list of 2-tuples" reality then you can use variable/dynamic keys, e.g.

key = :label
value = "some label"
options = [{key, value}]
IO.inspect(something, options)
Related