Elixir Typespecs & Behaviours
Elixir is dynamically typed, but it gives you two ways to describe contracts in code. Typespecs document the types a function accepts and returns, and behaviours define a set of functions a module must implement. Since Elixir 1.17 the compiler also includes a gradual type checker that finds some type errors by itself, even without specs.
Typespecs
A @spec sits right above a function and describes its arguments and return value. @type defines your own named types:
defmodule Geo do
@typedoc "A latitude/longitude pair in degrees"
@type coord :: {float(), float()}
@spec distance_km(coord(), coord()) :: float()
def distance_km({lat1, lon1}, {lat2, lon2}) do
to_rad = fn deg -> deg * :math.pi() / 180 end
dlat = to_rad.(lat2 - lat1)
dlon = to_rad.(lon2 - lon1)
a =
:math.sin(dlat / 2) ** 2 +
:math.cos(to_rad.(lat1)) * :math.cos(to_rad.(lat2)) * :math.sin(dlon / 2) ** 2
Float.round(6371 * 2 * :math.asin(:math.sqrt(a)), 1)
end
@spec nearest(coord(), [{String.t(), coord()}]) :: {String.t(), float()} | nil
def nearest(_from, []), do: nil
def nearest(from, places) do
places
|> Enum.map(fn {name, coord} -> {name, distance_km(from, coord)} end)
|> Enum.min_by(fn {_name, km} -> km end)
end
end
lisbon = {38.72, -9.14}
IO.inspect(Geo.distance_km(lisbon, {40.42, -3.70}))
IO.inspect(Geo.nearest(lisbon, [{"Paris", {48.86, 2.35}}, {"Porto", {41.15, -8.61}}]))
IO.inspect(Geo.nearest(lisbon, []))503.0
{"Porto", 274.0}
nil
Specs don't change how code runs. They are read by documentation tools (ExDoc shows them), by your editor, and by Dialyzer (via the dialyxir package: mix dialyzer), which analyses the whole program and reports calls that can never succeed.
Common built-in types
| Type | Meaning |
|---|---|
integer(), float(), number() |
numbers (non_neg_integer(), pos_integer() too) |
boolean(), atom(), :ok |
booleans, any atom, one specific atom |
String.t() |
a UTF-8 string (binary() is any binary) |
list(t), [t] |
a list of t |
map(), %{key: t} |
maps |
{t1, t2} |
a tuple |
t1 | t2 |
either type |
keyword(), keyword(t) |
keyword lists |
any(), term() |
anything |
pid(), reference(), fun(), (integer() -> String.t()) |
processes, refs, functions |
%User{}, User.t() |
a struct (by convention modules define t/0) |
A struct module usually defines its own t type:
defmodule User do
@type t :: %__MODULE__{name: String.t(), age: non_neg_integer() | nil}
defstruct [:name, :age]
endThe built-in type checker
The compiler infers types from patterns and guards, and warns when a call can never work. Here to_fahrenheit/1 only accepts a {:celsius, number} tuple, and another module calls it with a bare float. The program below prints nothing itself; the output is the compiler's warning:
defmodule Temperature do
def to_fahrenheit({:celsius, c}) when is_number(c), do: c * 9 / 5 + 32
end
defmodule Weather do
def report, do: Temperature.to_fahrenheit(21.5)
end warning: incompatible types given to Temperature.to_fahrenheit/1:
Temperature.to_fahrenheit(21.5)
given types:
-float()-
but expected one of:
dynamic({:celsius, term()})
typing violation found at:
│
6 │ def report, do: Temperature.to_fahrenheit(21.5)
│ ~
│
└─ /w/main.exs:6:31: Weather.report/0
It is gradual: code it cannot reason about is treated as dynamic() and accepted. Each Elixir release adds more checks.
Behaviours
A behaviour is a list of callbacks, defined with @callback. A module that implements it declares @behaviour Name and defines every callback; the compiler warns if one is missing. GenServer, Supervisor, Application and Plug are all behaviours. This lets you write code that works with any implementation, chosen at runtime:
defmodule Notifier do
@callback deliver(to :: String.t(), text :: String.t()) :: :ok | {:error, term()}
@callback name() :: String.t()
def send_all(notifier, recipients, text) do
for to <- recipients do
{to, notifier.deliver(to, text)}
end
end
end
defmodule EmailNotifier do
@behaviour Notifier
@impl Notifier
def name, do: "email"
@impl Notifier
def deliver(to, text) do
if String.contains?(to, "@") do
IO.puts("[email to #{to}] #{text}")
:ok
else
{:error, :invalid_address}
end
end
end
defmodule SmsNotifier do
@behaviour Notifier
@impl Notifier
def name, do: "sms"
@impl Notifier
def deliver(to, text) do
IO.puts("[sms to #{to}] #{String.slice(text, 0, 20)}")
:ok
end
end
for notifier <- [EmailNotifier, SmsNotifier] do
IO.puts("using #{notifier.name()}:")
IO.inspect(Notifier.send_all(notifier, ["ana@example.com", "+351900000000"], "Your order has shipped!"))
endusing email:
[email to ana@example.com] Your order has shipped!
[{"ana@example.com", :ok}, {"+351900000000", {:error, :invalid_address}}]
using sms:
[sms to ana@example.com] Your order has shipp
[sms to +351900000000] Your order has shipp
[{"ana@example.com", :ok}, {"+351900000000", :ok}]
The module is just a value (notifier), so swapping implementations is easy, for example a fake notifier in tests. That is the basis of the popular Mox testing library.
Optional callbacks and checking an implementation
defmodule Plugin do
@callback init(keyword()) :: {:ok, term()}
@callback describe() :: String.t()
@optional_callbacks describe: 0
end
defmodule Minimal do
@behaviour Plugin
@impl true
def init(opts), do: {:ok, opts}
end
IO.inspect(Plugin.behaviour_info(:callbacks) |> Enum.sort())
IO.inspect(function_exported?(Minimal, :describe, 0))
IO.inspect(Minimal.init(level: 2))[describe: 0, init: 1]
false
{:ok, [level: 2]}
Test yourself
Do typespecs change how a function runs?
- Yes, arguments are converted to the declared types
- Yes, wrong types raise at runtime
- No, they are documentation and input for tools like Dialyzer
- Only in production
What does @behaviour Notifier plus a missing callback produce?
- A runtime crash
- A compile-time warning
- Nothing
- A syntax error
What is the difference between a behaviour and a protocol?
- None
- Behaviours dispatch on the module you pick; protocols dispatch on the type of the data
- Protocols are only for structs
- Behaviours are only for GenServers