[erlang-questions] void() in type specs
Fri Nov 18 20:11:47 CET 2011
On 11/18/11 15:25, Olivier BOUDEVILLE wrote:
> How can we define a type spec for a function which is useful only for
> its side effects (not returning anything of interest to the caller)?
> In the documentation of various modules there are functions that are
> said to return 'void()' (ex: erlang:purge_module/1), however the
> compiler complains if I want to use it in my code ("type void()
> undefined") and void() is not mentioned in
> I imagine we could define such a "don't care"-type with a '-opaque
> void() :: any().' but wouldn't it be more practical if it was a built-in
> keyword? Moreover it could allow Dialyzer to check that the result is
> indeed never used (or maybe I overlooked something?)
There is no void() in Erlang and functions that return always return
some value. To my mind, the only sensible values for don't care returns
are atoms. The atoms 'ok' or 'void' are among the best such values you
can get. Whether callers are supposed to check or depend on this value
or not is a different matter. If you don't care, simply write these
functions as follows:
... DO LOTS OF SIDE-EFFECTS HERE ...,
... MORE SIDE EFFECTS ...,
and spec them as:
-spec foo(...SOME TYPES...) -> 'ok'.
or if you prefer,
-type void() :: 'ok'.
-spec foo(...SOME TYPES...) -> void().
If you absolutely want to guarantee that there is no pattern matching
with this void(), choose some weird atom for their return (eg. 'VoiD')
and then declare this return value opaque:
-opaque void() :: 'VoiD'.
Dialyzer will then warn you for all cases that you trying to explicitly
pattern match with this return.
But, out of curiosity, why guaranteeing that there is no matching with
whatever happens to be used for void() is so important to you?
More information about the erlang-questions