Search code examples
elixirapplyargs

Elixir Kernel.apply/2 and Kernel.apply/3 alternatives?


I'm creating a task that executes a function dynamically. This function is different each time, and so are the number of arguments ([1, "hi", :a]), so I was using Kernel.apply/2.

defp create_task(f, args) do
    Task.async(fn -> apply(f, args) end)
end

But I'm unable to get this to work with private functions (declared using defp):

create_task(&__MODULE__.my_private_fun/3, args)

Solution

  • If the function you're passing is defined using defp in a module, then there is no way you can call it from outside. But you can still call it if it's in the same module:

    create_task(&my_private_fun/3, args)
    

    The important thing to note here is that there is no getting around the fact that you have to specify the function arity (without macros), so why not just call the function directly?