TExcelTAD
Home › Elixir › Elixir Protocols

Elixir Protocols

A protocol defines a set of functions that different data types can implement in their own way. It is Elixir's tool for polymorphism: one function name, many implementations, chosen by the type of the first argument. You have already used protocols: Enum works on lists, maps and ranges because they all implement Enumerable, and string interpolation works because of String.Chars.

Defining and implementing a protocol

elixir · try it yourself
defprotocol Describe do
  @doc "Returns a short human description"
  def describe(value)
end

defimpl Describe, for: Integer do
  def describe(n) when n < 0, do: "a negative number"
  def describe(n), do: "the number #{n}"
end

defimpl Describe, for: BitString do
  def describe(s), do: "a #{String.length(s)}-letter string"
end

defimpl Describe, for: List do
  def describe([]), do: "an empty list"
  def describe(list), do: "a list of #{length(list)} items"
end

for value <- [42, -1, "hello", [], [1, 2, 3]] do
  IO.puts(Describe.describe(value))
end
the number 42
a negative number
a 5-letter string
an empty list
a list of 3 items

Built-in types you can implement for: Atom, BitString (strings), Float, Function, Integer, List, Map, PID, Port, Reference, Tuple, plus any struct.

If no implementation exists for a type, calling the protocol raises Protocol.UndefinedError:

elixir · try it yourself
defprotocol Area do
  def area(shape)
end

defimpl Area, for: Map do
  def area(%{w: w, h: h}), do: w * h
end

IO.inspect(Area.area(%{w: 2, h: 3}))

try do
  Area.area({2, 3})
rescue
  e in Protocol.UndefinedError -> IO.puts(Exception.message(e))
end
6
protocol Area not implemented for Tuple

Got value:

    {2, 3}

Protocols for your structs

Protocols really shine with structs. Each struct type gets its own implementation, and code that uses the protocol works with any type, including ones added later by other libraries. (As in the Structs lesson, code that builds structs defined in the same script goes inside a module, here Demo.)

elixir · try it yourself
defprotocol Notify do
  def message(event)
end

defmodule OrderShipped do
  defstruct [:order_id, :carrier]
end

defmodule PasswordChanged do
  defstruct [:user]
end

defimpl Notify, for: OrderShipped do
  def message(e), do: "Order ##{e.order_id} is on its way with #{e.carrier}."
end

defimpl Notify, for: PasswordChanged do
  def message(e), do: "Hi #{e.user}, your password was changed."
end

defmodule Demo do
  def run do
    events = [%OrderShipped{order_id: 1001, carrier: "DHL"}, %PasswordChanged{user: "Rosa"}]
    Enum.each(events, &IO.puts(Notify.message(&1)))
  end
end

Demo.run()
Order #1001 is on its way with DHL.
Hi Rosa, your password was changed.

Implementing built-in protocols

Implementing Elixir's own protocols makes your structs feel native:

Protocol Gives you
String.Chars to_string/1 and "#{value}" interpolation
Inspect how IO.inspect / IEx print your struct
Enumerable every Enum and Stream function
Collectable Enum.into/2 and for ... into:
JSON.Encoder JSON.encode!/1 (Elixir 1.18+ built-in JSON)
elixir · try it yourself
defmodule Temperature do
  defstruct [:degrees, unit: :c]
end

defimpl String.Chars, for: Temperature do
  def to_string(%{degrees: d, unit: :c}), do: "#{d} °C"
  def to_string(%{degrees: d, unit: :f}), do: "#{d} °F"
end

defimpl Inspect, for: Temperature do
  def inspect(t, _opts), do: "#Temperature<#{t}>"
end

defmodule Demo do
  def run do
    today = %Temperature{degrees: 23}
    IO.puts("Today it is #{today}")
    IO.inspect([today, %Temperature{degrees: 70, unit: :f}])
  end
end

Demo.run()
Today it is 23 °C
[#Temperature<23 °C>, #Temperature<70 °F>]

Deriving and fallbacks

Some protocols can be derived: @derive asks the protocol to generate an implementation from the struct's fields. @fallback_to_any true lets a protocol provide a default implementation for types that don't have their own:

elixir · try it yourself
defprotocol Size do
  @fallback_to_any true
  def size(data)
end

defimpl Size, for: Map do
  def size(map), do: map_size(map)
end

defimpl Size, for: Any do
  def size(_), do: :unknown
end

defmodule Secret do
  @derive {Inspect, only: [:name]}
  defstruct [:name, :password]
end

defmodule Demo do
  def run do
    IO.inspect(Size.size(%{a: 1, b: 2}))
    IO.inspect(Size.size(:atom))
    IO.inspect(%Secret{name: "db", password: "hunter2"})
  end
end

Demo.run()
2
:unknown
#Secret<name: "db", ...>

Deriving Inspect with only: is a good habit for structs holding secrets: passwords never end up in logs.

Protocols vs behaviours

Protocol Behaviour
Dispatches on the data type of the first argument the module you choose to call
Example Enumerable, String.Chars GenServer, Plug
Defined with defprotocol / defimpl @callback / @behaviour

Test yourself

How does Elixir choose which protocol implementation to run?

  1. By the module that calls it
  2. By the data type of the first argument
  3. By the order of defimpl blocks
  4. Randomly

Which protocol makes "#{value}" work for your struct?

  1. Inspect
  2. String.Chars
  3. Enumerable
  4. Collectable

What is raised when a protocol has no implementation for a value's type?

  1. FunctionClauseError
  2. Protocol.UndefinedError
  3. ArgumentError
  4. Nothing, it returns nil