Can not find function

I have following code snippet:

defmodule SapOdataService.Auth.UserLogin do

  alias SapOdataService.Protocols.Auth

  @url_login Application.get_env(:service, :login)

  @enforce_keys [:username, :password]
  defstruct [:username, :password]
  @type t :: %__MODULE__{username: String.t, password: String.t}

  defimpl Auth do
    def sign_in(user) do

      basic_auth = create_auth_token(user.username, user.password)
    end

  end

  # private functions
  @spec create_auth_token(String.t, String.t) :: {String.t, String.t}
  defp create_auth_token(username, password) do
    encoded = "Basic " <> Base.encode64("#{username}:#{password}")
    {"Authorization", encoded}
  end

end

So when I try to compile to code, I’ve got following error:

== Compilation error on file lib/auth/user_login.ex ==
** (CompileError) lib/auth/user_login.ex:15: undefined function create_auth_token/2
    (stdlib) lists.erl:1338: :lists.foreach/2
    lib/auth/user_login.ex:12: (module)
    (stdlib) erl_eval.erl:670: :erl_eval.do_apply/6

That because of the statement:

basic_auth = create_auth_token(user.username, user.password)

And I change to

basic_auth = UserLogin.create_auth_token(user.username, user.password)

then the compiler does not complain at all.

Why do I have to put the module name in front of it? It is in the same module?

Thanks

The compiler won’t complain, but I don’t think it will work.

A private function is local to a module, it can’t be called from other modules. defimpl defines a separate module. Anything you call from there must be either inside the defimpl itself or public functions on other modules.

1 Like

Thanks so much.