定義行為

你可以通過在模組中新增 -callback 指令來定義自己的行為。例如,如果實現你的行為的模組需要一個 foo 函式,它接受一個整數並返回一個原子:

-module(my_behaviour).
-callback foo(integer()) -> atom().

如果你在另一個模組中使用此行為,編譯器將發出警告,如果它不匯出 foo/1,Dialyzer 將警告型別是否正確。有了這個模組:

-module(bar).
-behaviour(my_behaviour).
-export([foo/1]).

foo([]) ->
    {}.

並執行 dialyzer --src bar.erl my_behaviour.erl,你得到這些警告:

bar.erl:5: The inferred type for the 1st argument of foo/1 ([]) is not a supertype of integer(), which is expected type for this argument in the callback of the my_behaviour behaviour
bar.erl:5: The inferred return type of foo/1 ({}) has nothing in common with atom(), which is the expected return type for the callback of my_behaviour behaviour