Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use defdelegate in elixir?

Tags:

elixir

Could somebody provide a simple example for defdelegate. I couldn't find any, making it hard to understand.

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

I get undefined function world/0 for the below:

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

I would like to delegate Other.world to Dummy.hello

like image 825
Bala Avatar asked Jul 24 '16 18:07

Bala


1 Answers

Two things:

  1. You got the name and as: wrong. as: should contain the name of the function in the target module and the first argument should be the name to define in the current module.

  2. The argument to as needs to be an atom.

Final working code:

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

Output:

hello from dummy
like image 173
Dogbert Avatar answered Nov 02 '22 03:11

Dogbert