[erlang-questions] Temporarily violating record type constraints annoys dialyzer

Brujo Benavides elbrujohalcon@REDACTED
Mon Nov 12 12:11:31 CET 2018

Hi Roger,

	According to how you use your record, its spec should actually be…

-record widget {
   id :: undefined | binary(),
   name :: undefined | binary(),
   size :: undefined | integer()

	That will silence dialyzer or, putting it in the right perspective: That will be a spec that matches how your code actually treats that record.
	And that’s because: What happens if Props doesn’t have a tuple for name?

	If not having a {name, Name} tuple in Props is an invalid scenario, you should raise some sort of error.
	In that case I would recommend you to keep the record definition as-is, but fill the whole record at once:

parse_widget(Props) ->
    id = get_value(id, Props),
    name = get_value(name, Props),

get_value(Key, Props) ->
  {Key, Value} = lists:keyfind(Key, 1, Props),

	That way, get_value/2 will raise an error if a property is missing.

	If not having a {name, Name} tuple in Props is a valid scenario but you still don’t want that record property to be undefined, you will need a sane default for it.
	In that case, you should amend your record definition as…

-record widget {
   id = <<>> :: binary(),
   name = <<>> :: binary(),
   size = 0 :: integer()

	Hope this helps :)

Brujo Benavides <http://about.me/elbrujohalcon>

> On 12 Nov 2018, at 07:58, Roger Lipscombe <roger@REDACTED> wrote:
> I've got a record defined as follows (e.g., and very simplified):
> -record widget {
>    id :: binary(),
>    name :: binary(),
>    size :: integer()
> }.
> I parse that from (e.g.) a proplist:
> parse_widget(Props) ->
>    parse_widget(Props, #widget{}).
> parse_widget([{name, Name} | Rest], Acc) ->
>    parse_widget(Rest, Acc#widget { name = Name });
> % etc.
> Dialyzer isn't happy that my fields are initially set to 'undefined',
> even though this only occurs during the parsing step, and isn't a big
> deal.
> What can I do to deal with this? Either re-structuring my code or
> persuading dialyzer that it's OK would both be acceptable.
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20181112/94da3a3a/attachment.htm>

More information about the erlang-questions mailing list