Behaviours in Elixir
In Elixir, a behaviour is a contract between modules. One module declares the functions another must provide, and the compiler checks every adopter against that list. It is the mechanism behind OTP: a GenServer is a behaviour, and the callbacks a server writes are the functions the behaviour requires. Protocols dispatch on the type of a value; behaviours check a module at compile time, and a caller picks the module it wants.
@callback declares the contract
@callback states a function the adopter must write, with its types. The declaration has no body: it records the name, the arity and the types for the compiler and for the documentation:
printer.exs
defmodule Printer do @callback format(term) :: String.t() end defmodule Console do @behaviour Printer @impl true def format(text), do: ">> #{text}" end IO.puts(Console.format("hello"))
elixir printer.exs
>> hello
Printer is a module like any other; the attribute is what makes it a behaviour. term() accepts any value and String.t() is the type of a binary, which is the contract of the function. A caller that takes a module of this behaviour can call format/1 and knows what comes back, whichever module it was given.
@behaviour adopts it
@behaviour Printer tells the compiler that the module promises the callbacks of Printer. The promise does not import the functions or change the calls; it adds a check at compile time and a line of documentation that names the role the module plays. A module may adopt several behaviours, and one behaviour may require several callbacks.
@impl marks the callback
@impl true above a function says that the function implements a callback. The compiler checks that claim: a name or arity that the behaviour does not declare gets a warning, and a callback written without @impl in a module that has behaviours gets one too. Marking the callbacks keeps the contract visible in the source, where a reader looks for it.
The compiler checks the contract
The check is the reason to write a behaviour at all. A module that adopts a behaviour and forgets a callback compiles with a warning that names the missing function and the module. The warning below is the one a reader meets first, and it is also the mistake of the last section.
GenServer is a behaviour
OTP is a set of behaviours. use GenServer is the short form of adopting the GenServer behaviour: it requires the module, injects the default implementations of the optional callbacks, and leaves the required ones to the module. A minimal server writes init/1 and one handle_call/3:
genserver.exs
defmodule Counter do use GenServer def start_link(n), do: GenServer.start_link(__MODULE__, n) @impl true def init(n), do: {:ok, n} @impl true def handle_call(:get, _from, n), do: {:reply, n, n} end {:ok, pid} = Counter.start_link(5) IO.puts(GenServer.call(pid, :get))
elixir genserver.exs
5
init/1 returns the initial state, and handle_call/3 answers a call with {:reply, answer, new_state}. The callbacks are the behaviour of GenServer, the process and the message loop come from the library, and the GenServer lesson builds a full server on the same three lines.
The mistake: a missing callback
A module that adopts a behaviour and does not implement one of its callbacks still compiles, because a warning is not an error by default. The warning names the callback and the module, and the program runs with a module that does not fulfil its contract:
missing.exs
defmodule Printer do @callback format(term) :: String.t() end defmodule Silent do @behaviour Printer end IO.puts("compiled")
elixir missing.exs
compiled
warning: function format/1 required by behaviour Printer is not implemented (in module Silent)
│
5 │ defmodule Silent do
│ ~~~~~~~~~~~~~~~~~~~
│
└─ missing.exs:5: Silent (module)
The program prints its line first; the warning is written to the error stream and underlines the module it is about. The fix is the callback, and a pipeline that runs mix compile --warnings-as-errors turns this warning into a failed build, which is how a project keeps a behaviour honest. The OTP behaviours mark their required callbacks the same way, which is why a GenServer that forgets init/1 warns at compile time rather than failing at the first call.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
@callback format(term) :: String.t()declare?Answer
A function an adopting module must implement, with its types
The callback is the contract of the behaviour; the adopter writes the body.
-
What does
@behaviour Printerdo in a module?Answer
It promises the callbacks of Printer and lets the compiler check them
A behaviour is a compile-time contract, not an import of code.
-
What is
@impl truefor?Answer
It marks a function as the implementation of a callback
The attribute documents the role of the function and lets the compiler check the claim.
-
What happens when an adopting module omits a required callback?
Answer
The compiler warns that the callback is not implemented
The check is a warning by default; warnings-as-errors turns it into a failed build.
-
What does a protocol have that a behaviour does not?
Answer
Dispatch on the run-time type of a value
A protocol picks an implementation by type; a behaviour checks the module that adopts it.
-
What does this program print?
defmodule Printer do @callback format(term) :: String.t() end defmodule Console do @behaviour Printer @impl true def format(text), do: ">> #{text}" end IO.puts(Console.format("hello"))Answer
>> hello
The callback is implemented and called, and IO.puts/1 prints the decorated text.
-
What does this program print?
defmodule Printer do @callback format(term) :: String.t() end defmodule Console do @behaviour Printer @impl true def format(text), do: ">> #{text}" end IO.puts(Console.format(42))Answer
>> 42
The callback accepts term(), and interpolation turns 42 into text.
-
What does this program print?
defmodule Printer do @callback format(term) :: String.t() end defmodule Console do @behaviour Printer @impl true def format(text), do: ">> #{text}" end IO.puts(Enum.map_join([1, 2], ", ", &Console.format/1))Answer
>> 1, >> 2
map_join applies the callback to each element and joins the results.
-
What does
init/1return in a GenServer?Answer
{:ok, state} with the initial state
The callback returns a tagged state, which the server keeps between calls.
-
What does this program print?
defmodule Counter do use GenServer def start_link(n), do: GenServer.start_link(__MODULE__, n) @impl true def init(n), do: {:ok, n} @impl true def handle_call(:get, _from, n), do: {:reply, n, n} end {:ok, pid} = Counter.start_link(5) IO.puts(GenServer.call(pid, :get))Answer
5
The call is answered from the state, and the reply 5 is printed.
Автор статьи: Arthur Isaev