How to override a function or variable type in Elixir and Dialyzer?

641 views Asked by At

I'm using Elixir and I'm getting a Dialyzer (via Dialyxir) error that says

The pattern
variableVdate

can never match, because previous clauses completely cover the type
{:error, :badarg}.

Here is the code

date = Timex.DateTime.from_seconds(0)

case date do
  {:error, :badarg} ->
    {:error, "Bad Date"}

  date ->
    {:ok, date}
end

I believe this is because Timex.DateTime.from_seconds has an incorrect type spec.

They define it as

@spec from_seconds(non_neg_integer) :: DateTime.t :: {:error, atom}

But I think it is supposed to be

@spec from_seconds(non_neg_integer) :: DateTime.t | {:error, atom}

Is there some way to workaround this issue perhaps by overriding the type spec or the date type in some way?

For other reasons, I'm unable to upgrade Timex to version 3.

1

There are 1 answers

0
Joe Harrow On

I think this is because you're calling from_seconds/1 with a specific value, 0, so the return is not variable. My guess is running this with seconds as a passed in variable might work:

case Timex.DateTime.from_seconds(seconds) do
  {:error, :badarg} ->
    {:error, "Bad Date"}

  date ->
    {:ok, date}
end