1

I have just started learning Elixir and I am unable to figure out how import works in Elixir. When I import a module into another module using import I am unable to call the imported function by using the module in which it is imported.

But I am able to call function of imported module inside function in the module which it was imported.

defmodule A do
  def func do
   IO.puts("func called")
  end
end

defmodule B do
  import A
end

A.func # o/p: "func called"
B.func # (UndefinedFunctionError) undefined function: B.func/0

defmodule B do
  import A

  def func2 do
    func
  end
end

B.func2 # o/p "func called"

I am unable to figure out why B.func not works while I was able to call func from func2. Is there some kind of theory that I am missing. Coming from the Ruby background this behaviour looks odd to me. Please can anybody help me out or point me to some good resource to read.

0

1 Answer 1

5

import does not really import anything in the way many other languages do. All it does is makes the imported module's exported functions accessible from the current namespace. To quote the docs

We use import whenever we want to easily access functions or macros from other modules without using the fully-qualified name.

If you want A.func and B.func to point to the same function you have a couple options. The first is simple - make a wrapper function:

defmodule B do
  def func do
     A.func
  end
end

If you want some more complex inheritance type stuff you can look into creating a __using__ macro with defoverridable and super

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the links and detailed answer
Another way to put it is that import is lexical, this article can hopefully clarify it: thepugautomatic.com/2015/11/elixir-scoping Also, avoid the "inheritance like" stuff, it is encouraged only for callbacks. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.