Warning about unused import & undefined/private function error

The code below throws the error below, and I did not expect that, so I was wondering if this is intended behaviour. If so, how would one define a code structure like this? The idea is to have a module Foo that holds some shared functions, imported into several modules similar to Bar, which are then called from yet another module Baz.

defmodule Foo do
  def foo do
    "bar"
  end
end

defmodule Bar do
  import Foo
end

defmodule Baz do
  def baz do
    Bar.foo()
  end
end

Baz.baz()

$ warning: unused import Foo
$ ** (UndefinedFunctionError) undefined function: Bar.foo/0

Hi Beno,
This is expected behavior. Per h import:

import/2 allows one to easily access functions or macros from others modules
without using the qualified name.

so it’s making the imported functions available to easily call within your module, nothing more. Thus, in your use case, the following is probably what you wanted.

defmodule Baz do
  import Foo

  def baz do
    foo
  end
end

If you find yourself wanting to import certain functions a lot you can use the use macro like this:

defmodule Shared do
  defmacro __using__(_opts) do
    quote do
      import Foo
    end
  end
end

defmodule Baz do
  use Shared

  def baz do
    foo
  end
end

see h use for some more docs around this feature.

2 Likes

You’re the best. Thanks!

2 Likes

Actually, look at defdelegate:

defmodule Foo do
  def foo do
    "bar"
  end
end

defmodule Bar do
  defdelegate foo, to: Foo
end

defmodule Baz do
  def baz do
    Bar.foo()
  end
end
6 Likes