Erlang Language Behaviours Optional callbacks in a custom behaviour



By default, any function specified in a -callback directive in a behaviour module must be exported by a module that implements that behaviour. Otherwise, you'll get a compiler warning.

Sometimes, you want a callback function to be optional: the behaviour would use it if present and exported, and otherwise fall back on a default implementation. To do that, write the -callback directive as usual, and then list the callback function in an -optional_callbacks directive:

-callback bar() -> ok.

If the module exports bar/0, Dialyzer will still check the type spec, but if the function is absent, you won't get a compiler warning.

In Erlang/OTP itself, this is done for the format_status callback function in the gen_server, gen_fsm and gen_event behaviours.