Erlang / Erlang Advanced Interview questions
How do you define and use a custom behavior with the -callback attribute?
Beyond OTP's built-in behaviors (gen_server, supervisor, and so on), you can define your own reusable
process pattern by declaring the required callbacks a module implementing your behavior must export, using the
-callback attribute.
%% my_plugin.erl - the behavior definition -module(my_plugin). -callback handle_event(Event :: term(), State :: term()) -> {ok, NewState :: term()}. %% logger_plugin.erl - a module implementing it -module(logger_plugin). -behaviour(my_plugin). -export([handle_event/2]). handle_event(Event, State) -> io:format("event: ~p~n", [Event]), {ok, State}.
The -callback declaration lets Dialyzer and the compiler verify that any module claiming
-behaviour(my_plugin) actually exports a matching handle_event/2, warning at compile
time if it's missing — giving you the same "pluggable module with an enforced contract" pattern OTP's own
behaviors use, for your own domain-specific extension points.
More Related questions...