如何在灵药中使用defdelegate?

时间:2016-07-24 18:57:23

标签: elixir

有人可以为defdelegate提供一个简单的例子。我找不到任何东西,让人难以理解。

defmodule Dummy do
  def hello, do: "hello from dummy"
end

我得到undefined function world/0以下内容:

defmodule Other do
  defdelegate hello, to: Dummy, as: world
end

我想将Other.world委托给Dummy.hello

1 个答案:

答案 0 :(得分:19)

两件事:

  1. 你得到了名字而as:错了。 as:应该包含目标模块中函数的名称,第一个参数应该是当前模块中要定义的名称。

  2. as的参数必须是原子。

  3. 最终工作代码:

    defmodule Dummy do
      def hello, do: "hello from dummy"
    end
    
    defmodule Other do
      defdelegate world, to: Dummy, as: :hello
    end
    
    IO.puts Other.world
    

    输出:

    hello from dummy