Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 36 ยท Tools and Testing

Types, specs and Dialyzer

Document Erlang functions with -spec and -type, define custom and opaque types, run Dialyzer to find discrepancies, and understand success typing.

Erlang is dynamically typed: variables carry no declared type, and many mistakes appear only at run time. Yet large systems need documentation and checking. Erlang solves this with type specifications that are optional, checked by a separate tool, Dialyzer (DIscrepancy AnaLYZer for ERlang), and never change how code runs. Specs also feed documentation and editor tooling.

Specs for functions

A -spec states the argument and result types of a function:

ERLANG
-module(shapes).
-export([area/1, scale/2]).

-spec area({circle, number()} | {rect, number(), number()}) -> float().
area({circle, R})  -> math:pi() * R * R;
area({rect, W, H}) -> float(W * H).

-spec scale(number(), number()) -> number().
scale(Factor, Value) -> Factor * Value.

The | separates alternatives (a union). Put the spec directly above the function, with the same name and arity. You can give several clauses for functions with different shapes:

ERLANG
-spec first([T]) -> {ok, T} | error.
first([H | _]) -> {ok, H};
first([])      -> error.

Here T is a type variable: the result type depends on the argument.

Built-in types

Type Meaning
integer(), pos_integer(), non_neg_integer(), 0..255, byte() integers and ranges
float(), number() floats; integer or float
atom(), ok, error any atom; specific atoms (literal types)
binary(), string(), iodata() binaries; list of characters; text for output
list(T) or [T], [T, ...] list; non-empty list
tuple(), {atom(), integer()} any tuple; a tuple with typed elements
map(), #{name := string(), age => integer()} maps; := required key, => optional key
pid(), reference(), fun(), fun((integer()) -> boolean()) processes, references, functions
any(), term(), none(), no_return() everything; nothing; never returns
boolean(), timeout(), module(), mfa() common aliases

Defining your own types

ERLANG
-type color() :: red | green | blue.
-type point() :: {X :: number(), Y :: number()}.
-type user()  :: #{name := binary(), age := non_neg_integer(), email => binary()}.

-record(account, {id :: pos_integer(), owner :: binary(), balance = 0 :: integer()}).

-export_type([color/0, point/0]).

-spec move(point(), point()) -> point().
move({X, Y}, {DX, DY}) -> {X + DX, Y + DY}.

-export_type makes a type usable from other modules as shapes:color(). An opaque type hides its structure from outside code:

ERLANG
-opaque stack() :: [term()].
-export_type([stack/0]).

Callers must treat stack() as a black box and use your functions; Dialyzer complains if they inspect it directly.

Dialyzer: success typing

Run it with rebar3 dialyzer. The first run builds a PLT (persistent lookup table) of types for OTP and takes minutes; later runs are fast. Dialyzer's philosophy is unusual: it is never wrong. It reports only code that is certain to fail at some point, and says nothing about code that merely might. This means no false alarms, but also that it does not find every bug.

Typical warnings:

TEXT
shapes.erl:12: The call shapes:area({square, 3}) will never return since it differs in the 1st argument from the success typing arguments: ({'circle', number()} | {'rect', number(), number()})

shapes.erl:20: Function broken/0 has no local return

shapes.erl:25: The pattern 'error' can never match the type {'ok', _}
  • "will never return": a call whose argument cannot be accepted by the function.
  • "has no local return": the function always crashes.
  • "can never match": dead code or a wrong assumption, a common sign of a bug.
  • "Invalid type specification": the -spec contradicts the code.

Dialyzer infers a success typing for each function from its clauses, and compares it with your spec and with each call site. A spec narrower than the inferred type is fine; a spec disjoint from it is an error.

Specs and Dialyzer

-spec and -type Documentation the tool can read
Dialyzer Finds code that must fail
No false alarms Silent about merely risky code
No runtime effect Specs never change execution

Types are optional, but they pay for themselves in big code bases.

1 / 2

Gradual adoption

You do not need to annotate everything. Start with public functions of each module, and with types of records and messages exchanged between processes. Specs on the callbacks of behaviours (gen_server) are inferred from the behaviour's own specs. A useful tip is to spec the messages:

ERLANG
-type request() :: {get, term()} | {put, term(), term()} | stop.
-spec handle_call(request(), gen_server:from(), state()) ->
          {reply, term(), state()}.

In rebar.config, tune the checks:

ERLANG
{dialyzer, [
    {warnings, [unmatched_returns, error_handling, unknown]},
    {plt_extra_apps, [jsx]}
]}.

unknown reports calls to modules missing from the PLT, which shows forgotten plt_extra_apps.

Run it: a type-check stand-in

The real Dialyzer cannot run here. This JavaScript stand-in is not Dialyzer; it checks arguments against a spec of union types at run time, so you can see the idea of "a call that cannot succeed".

JS Stand-in: checking a call against a spec

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Records versus maps in specs

A record is a tuple with a known tag and fixed fields, so #account{} is a precise type; Dialyzer can detect a wrong field name at compile time. Maps with := and => describe flexible structures such as JSON. Choose records for internal state of a server and maps for data crossing system boundaries.

Common mistakes

  • Writing a spec that is too wide (term() everywhere) and gets no help from the tool.
  • Expecting Dialyzer to catch every type error; it is conservative by design.
  • Forgetting debug_info in erl_opts; Dialyzer needs it.
  • Changing a type in one module and not rerunning on the callers.
  • Opaque types: pattern matching on them outside the owning module breaks the contract and is warned about.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What effect do -spec declarations have at run time?

    Specs are metadata. They never change execution.
  2. 2. What kind of warnings does Dialyzer give?

    Dialyzer is based on success typing and reports only certain discrepancies.
  3. 3. How do you write a map type where name is required and email optional?

    := marks required keys and => optional keys.
  4. 4. What does an -opaque type do?

    Dialyzer warns when code outside the module depends on an opaque type's internal structure.

Summary

  • -spec and -type document functions and data; they are optional and do not affect execution.
  • Types cover primitives, unions, lists, tuples, maps (:= and =>), records and function types.
  • -opaque hides representation; -export_type shares types across modules.
  • rebar3 dialyzer finds code that is sure to fail, with no false alarms but not every bug.
  • Add specs gradually, starting with public APIs and messages.

Next: Project: a chat room