2017-08-11 23 views
1

我想用一個module attribute@magic_constant在這兩個一個類型指定以及警衛:藥劑:在型號規格模塊屬性

defmodule Example do 
    @magic_constant 1 

    @type t :: @magic_constant 

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

當我嘗試用這種藥劑V1.5,將報告以下編譯錯誤:

== 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 

有沒有辦法在警衛和typepecs中使用常量?

回答

4

您可以使用unquote在typespec中注入module屬性的值。

defmodule Example do 
    @magic_constant 1 

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