Specs for Functions and Callbacks

The @spec specifies a function’s parameter count, types, and return-value type. It can appear anywhere in a module that defines the function, but by convention it sits immediately before the function definition, following any function documentation.

We’ve already seen the syntax:

@spec function_name( param1_type, …) :: return_type

Let’s see some examples. These come from the built-in Dict module.

Line 1 
@type​ key :: any
@type​ value :: any
@type​ keys :: [ key ]
@type​ t :: tuple | list ​# `t` is the type of the collection
@spec​ values(t) :: [value]
@spec​ size(t) :: non_neg_integer
@spec​ has_key?(t, key) :: boolean
@spec​ update(t, key, value, (value -> value)) :: t
Line 6

Get Programming Elixir now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.