When Specifications Are Used?

Understand when and why we use specifications in Elixir.

We'll cover the following

When we looked at @callback in the Behaviours lesson, we saw that we defined callbacks in terms of their parameter types and return values. For example, we might write the following:

@callback parse(uri_info :: URI.Info.t) :: URI.Info.t
@callback default_port() :: integer

The terms URI.Info.t and integer are examples of type specifications. The cool thing is that they’re implemented directly in the Elixir language itself. No special parsing is involved. This is a great illustration of the power of Elixir metaprogramming.

In the coming lessons, we’ll discuss how to specify types in Elixir. But before we do, there’s another question to address:

Why do we need specifications?

Elixir type specifications come from Erlang. It’s very common to see Erlang code where every exported public function is preceded by a -spec line. This is metadata that gives type information. The following code comes from the Elixir parser, which is currently written in Erlang. It says the return_error function takes two parameters, an integer, and any type, and it never returns.

-spec return_error(integer(), any()) -> no_return().
return_error(Line, Message) ->
      throw({error, {Line, ?MODULE, Message}}).
  • One of the reasons the Erlang folks do this is to document their code. We can read it inline while reading the source, and we can also read it in the pages created by their documentation tool.

  • The other reason is that they have tools such as Dialyzer that perform static analysis of Erlang code and report on some kinds of type mismatches.

These same benefits can apply to the Elixir code. We have the @spec module attribute for documenting a function’s type specification; in IEx, we have the s helper for displaying specifications and the t helper for showing user-defined types. We can also run Erlang tools such as dialyzer on compiled Elixir .beam files.

However, type specifications aren’t currently in wide use in the Elixir world. Whether we use them is a matter of personal taste.

Get hands-on with 1200+ tech skills courses.