Using -spec for callbacks when defining behaviours

Magnus Henoch <>
Wed Mar 17 15:26:51 CET 2010


Vlad Dumitrescu <> writes:

> - attach the -spec to the callback functions. I think that a simple
> way to do that is to have the module declaring the behaviour implement
> even the callbacks (as dummy functions) and then type specs can be
> attached to them. There might be problems with name conflicts, but I
> don't think there are that many behaviours out there besides the
> standard ones to be a problem. In the worst case, these dummy
> functions could be put in a separate module.

I was thinking about this the other day, and came up with the idea of
creating a new directive: -behaviour_spec.  It would look just like the
normal -spec directive, except that it describes the types of the
functions required by the behaviour.

It would be nice to be able parameterise those types somehow.  For
example, the State variable accepted and returned by almost all
functions in the gen_server behaviour obviously has type any(), but for
any given callback module the state should have a narrower type.  In
order to save typing and avoid mistakes, you'd want to specify that type
once and for all in that module.  I can't think of any good syntax for
that, though...

This is ugly but should get the idea across:

%% gen_server.erl
-behaviour_spec handle_call(any(), {pid(), any()}, State) -> {'reply', any(), State}.

%% my_callback.erl
-behaviour(gen_server).
-record(state, {foo}).
-behaviour_type(State, #state{}).

-- 
Magnus Henoch, 
Erlang Solutions
http://www.erlang-solutions.com/
---------------------------------------------------

---------------------------------------------------

WE'VE CHANGED NAMES!

Since January 1st 2010 Erlang Training and Consulting Ltd. has become ERLANG SOLUTIONS LTD.

www.erlang-solutions.com



More information about the erlang-questions mailing list