Why this erlang prog with type signature can compile?

Viewed 50

I have this prog:

-module(a).
-export([add/2]).
-export([add2/1]).

-spec add(integer(),integer())->integer().
add(A,B)->A+B.

add2(C)->C+add(1,"a").

I can compile this prog with no error.but I think I should got error for the line

add(1,"a").

in any static type language,it can't compile,so why erlang will compile this?how to
write the type signature so erlang can catch this error?If erlang can't,can elixir write the same prog but can catch this error?Thanks!

2 Answers

The Erlang compiler doesn't check type specs. You can use Dialyzer, included in Erlang, to check them:

dialyzer --src a.erl

It gives the following output:

  Proceeding with analysis...
a.erl:8: Function add2/1 has no local return
a.erl:8: The call a:add
         (1,
          "a") will never return since the success typing is 
         (number(),
          number()) -> 
          number() and the contract is 
          (integer(), integer()) -> integer()
 done in 0m0.19s
done (warnings were emitted)

The first time you run Dialyzer, it will complain that it doesn't have a PLT (a Persistent Lookup Table) for the standard applications. You can build it with:

dialyzer --build_plt --apps erts kernel stdlib mnesia
Related