Map Traps

Let’s explore some potential map traps we might run into.

These are some of the traps we might fall into if we’re not careful. Don’t be fooled by the fact that iex sorts small maps in the console for convenience. We cannot count on this ordering! If we need to enforce order, we should use lists.

Keyword lists

Keyword lists were the maps in Elixir before we had true maps. They are lists of two tuples, each with an atom key and any type for a value. They are preferred over maps due to the following function options they provide:

  • They allow duplicates.

  • They support specific syntactic sugar. For example, if the last argument in a function is a keyword list, we can omit the surrounding [], such as Elixir’s short-form functions:

 // With options, the non-sugared way.
def func_with_options("arg1", [verbose: true, indent: 4])
 // With options, with syntactic sugar.
def func_with_options("arg1", verbose: true, indent: 4)

Get hands-on with 1400+ tech skills courses.