Reputation: 838
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.
Upvotes: 1
Views: 1956
Reputation: 4284
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
Upvotes: 5