Search code examples
elixirfunction-parameter

Elixir - passing function parameter through


Say I have a function, that's slightly verbose and is called with the same arguments each time, this function is also required a lot to do some setup before any other functions from that module can be called within its callback.

SomeMod.called_a_lot(‘xx’, fn(y) ->
  SomeMod.needs_called_a_lot_to_be_called_first(‘do_stuff’)
end)

I imagine that I can wrap it like so:

defp easier_to_call(func) do
  SomeMod.called_a_lot(‘xx’, fn(y) -> func(y) end
end

then use it like so:

easier_to_call(fn(y) ->
  SomeMod.needs_called_a_lot_to_be_called_first(‘do_stuff’)
end)

How does one actually do this in Elixir?


Solution

  • Your syntax is just a bit off for calling anonymous functions. You will need to use

    func.(y)
    

    instead of

    func(y)
    

    since it is an anonymous function.

    See the Elixir Crash Course for a brief example.