O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required