5
votes

I would like to use a module attribute @magic_constant in both a typespec as well as guards:

defmodule Example do
    @magic_constant 1

    @type t :: @magic_constant

    def f(i) when i == 1 do
        :ok
    end
end

When I try this with Elixir v1.5, the following compile error is reported:

== Compilation error in file lib/example.ex ==
** (CompileError) lib/example.ex:4: type '@'(_) undefined
    (stdlib) lists.erl:1338: :lists.foreach/2
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
[1]    17240 exit 1     mix compile

Is there a way to use a constant in both guards and typespecs?

1

1 Answers

8
votes

You can use unquote to inject the value of the module attribute in the typespec.

defmodule Example do
  @magic_constant 1

  @type t :: unquote(@magic_constant)
end
iex(1)> t Example
@type t() :: 1