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 |
2 | @type value :: any |
3 | @type keys :: [ key ] |
4 | @type t :: tuple | list # `t` is the type of the collection |
5 | |
6 | @spec values(t) :: [value] |
7 | @spec size(t) :: non_neg_integer |
8 | @spec has_key?(t, key) :: boolean |
9 | @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.