The function hello does not have any conflicts & working perfectly fine.
defmodule User do
defstruct [:name]
end
defmodule Greeter do
def hello(%User{} = user) do
"Hello #{user.name}"
end
def hello(name) do
"Hello #{name}"
end
end
But if I add optional parameter to the first function, I got conflict error.
...
def hello(%User{} = user, opts \\ []) do
"Hello #{user.name}"
end
...
Error
def hello/1 conflicts with defaults from hello/2
Can anyone explain why and how this make sense?
def hello/1 conflicts with defaults from hello/2
This means that the compiler doesn't know if hello("foo") means:
hello/1 with "foo" as the argument.hello/2 with "foo" as the first argument and the default second argument.It doesn't know this because both have the same calling syntax, but the clauses could be implemented differently.
You can first declare the function signature with the default value, and then define the implementations that use that default value. I think it's best to just have one definition of the final result that returns "Hello #{name}", and wrap that behaviour in the other function clause:
def hello(user, opts \\ [])
def hello(%User{name: name}, opts), do: hello(name, opts)
def hello(name, _opts), do: "Hello #{name}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With