DEV Community

Cover image for What is an atom in Elixir?
Diego Novais
Diego Novais

Posted on Edited on

What is an atom in Elixir?

According to the Elixir documentation, an Atom is a constant whose value is own name. To some Ruby developers like me, an :atom is like a :symbol.

In Elixir, it is common to use atoms on lists, tuples, and maps:

defmodule Example do
  def example_params do
    # tupla
    tuple = {:ok, "This is a tuple"}

    # list
    list = [:slug, :title]

    # map
    map = %{
      name: "Diego",
      age: 35,
      country: "Brazil"
    }
  end
end
Enter fullscreen mode Exit fullscreen mode

A curiosity in Elixir is that the boolean true and false also is :atoms:

iex> true == :true
> true

iex> false == :false
> false

iex> is_atom(false)
> true

iex> is_boolean(:false)
> true

Enter fullscreen mode Exit fullscreen mode

In Elixir, we usually use atoms as a reference status for a given request:

defmodule ExampleController do
  #...

  def delete_person(conn, %{"id" => id}) do
    person = Person.get_person!(id)

    {:ok, _person} = Person.Repo.delete(person)

    conn
    |> put_flash(:info, "Person deleted successfully.")
    |> redirect(to: person_path(conn, :index))
  end
end
Enter fullscreen mode Exit fullscreen mode

In the example above, the atom :ok indicates that the delete request was executed successfully. And then a "flash message" was triggered with status :info indicating that "the person was deleted successfully" and, after, redirected to :index.

I hope that this content helps and makes sense to you!

Contacts
Email: contato@diegonovais.com.br
LinkedIn: https://www.linkedin.com/in/diegonovais/
Github: https://github.com/dnovais
Twitter: https://twitter.com/diegonovaistech

Top comments (0)