Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function def conflicts by adding optional parameter elixir

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?

like image 852
Khaino Avatar asked Mar 22 '26 00:03

Khaino


1 Answers

def hello/1 conflicts with defaults from hello/2

This means that the compiler doesn't know if hello("foo") means:

  • Call hello/1 with "foo" as the argument.
  • Call 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}"
like image 141
Adam Millerchip Avatar answered Mar 23 '26 16:03

Adam Millerchip