Can you refer to a function with optional arguments with the function/2 syntax? Is there another way to refer to them?

I’m creating a generic form LiveComponent that will work for creating and editing a few different kinds of schemas that share some common fields.

In order to do that, I need to be able to pass functions such as Items.change_item/1,2, Items.create_item/1, and Items.update_item/2.

If I’m barking up the wrong tree by passing in the functions like this, what other solution would be suitable for building a generic form like this? I’ve thought about creating a common changeset for the shared fields, but not sure that’s the correct solution either.

Optional arguments are a shorthand for defining a handful of function heads with different argument counts:

def foo(bar, baz \\ 1, wat \\ 2, huh \\ 3), do: ...

is a short way to write:

def foo(bar), do: foo(bar, 1, 2, 3)
def foo(bar, baz), do: foo(bar, baz, 2, 3)
def foo(bar, baz, wat), do: foo(bar, baz, wat, 3)
def foo(bar, baz, wat, huh), do: ...

Capturing one specific head with (eg &foo/3) results in a function that expects exactly three arguments.

3 Likes