【发布时间】:2020-01-01 22:29:01
【问题描述】:
我有一个包含任何函数的行为。
defmodule MyBehaviour do
@callback do_run( ? ) :: ? #the ? means I don't know what goes here
defmacro __using__(_) do
quote location: :keep do
@behaviour MyBehaviour
def run, do: MyBehaviour.run(__MODULE__, [])
def run(do_run_args), do: MyBehaviour.run(__MODULE__, do_run_args)
end
end
def run(module, do_run_args) do
do_run_fn = fn ->
apply(module, :do_run, do_run_args)
end
# execute do_run in a transaction, with some other goodies
end
end
defmodule Implementation do
use MyBehaviour
def do_run(arg1), do: :ok
end
Implemenation.run([:arg1])
这个想法是,通过实现MyBehaviour,模块Implementation 将拥有run([:arg1]) 函数,该函数将调用do_run(:arg1)。
如何为具有可变数量参数的函数编写@callback 规范?
我认为 @callback do_run(...) :: any() 可以工作,但 Dialyzer 给我一个错误 Undefined callback function do_run/1,所以我假设 ... 表示任何参数,但不是零参数。
实际上,我只有两种情况:零和一个 arg。 我想过像这样重载规范:
@callback do_run() :: any()
@callback do_run(any()) :: any()
但这需要两个 do_run 函数,因为在 Erlang 世界中,同名和不同的数量是两个独立的函数。
如果我做到@optional_callback,那么它们可能都不会实现。
@type 允许指定像 (... -> any()) 这样的任何数量的函数,所以我想应该可以对 @callback 做同样的事情。
是否可以在不重新实现行为的情况下正确指定这一点?
【问题讨论】: