...

/

Writing Type Specifications

Writing Type Specifications

Learn how to use typespecs and dialyxir to identify possible bugs in the code.

What are typespecs?

While Elixir isn’t a statically typed language, it does give the ability to specify types using typespecifications, or typespecs. Typespecs are specifications that communicate the intended use of a function.

For example, a function add/2 that adds two numbers a and b might have the following specification:

Press + to interact
@spec add(number, number) :: number
def add(a, b) do
a+b
end

Notice the syntax used to declare a specification. We use the @spec attribute to indicate that we’re defining a specification, and then declare the parameter types and the return type of the function. The syntax is similar to the syntax you used in the lesson Creating the Problem Behaviour, to define callbacks for your Problem behavior and to define your Chromosome type.

Defining typespecs for functions won’t do anything to improve the performance of the code; however, it does serve to enhance the readability of the code and can be used by dialyxir to find bugs and other problems ...