Intermediate Exercism • elixir

Access Behaviour

Lesson Overview

# Introduction

About

Elixir uses Behaviours to provide common generic interfaces while facilitating specific implementations for each module which implements the behaviour. One of those behaviours is the Access Behaviour.

The Access Behaviour provides a common interface for retrieving key-based data from a data structure. It is implemented for maps and keyword lists.

The Access module defines the callbacks required for the interface. The Map and Keyword modules then implement the required callbacks fetch/2, get_and_update/3, and pop/2

To use the behaviour, you may follow a bound variable with square brackets and then use the key to retrieve the value associated with that key. Maps support keys of any type, while keyword lists only atom keys.

# Atom as key
my_map = %{key: "my value"}
my_map[:key]
# => "my value"

# String as key
another_map = %{"key" => "my value"}
another_map["key"]
# => "my value"

If the key does not exist in the data structure, then nil is returned. This can be a source of unintended behavior, because it does not raise an error.

my_map = %{key: "my value"}
my_map[:wrong_key][:other_wrong_key]
# => nil

Note that nil itself implements the Access Behaviour and always returns nil for any key.

nil[:key]
# => nil

Structs do not implement the Access behaviour.

Access shortcuts


Originally from Exercism elixir concepts