The primary purpose of Imports and Aliases in Elixir is to make your code more human-readable. This post is part of the functional language series, and it is based on the remarkable book Elixir In Action by Sasa Juric.
Although it is possible to have several modules in the same source file, it is good code readability practice to put modules in separate files.
To be able to run the
position function from the image above, you need to write
Croatian.Basketball.position. This could quickly clutter your source code, so Elixir has
We first run
position function with a fully qualified Elixir name.
Then we used alias syntax to rename is to our preferred name,
Finally, we used
as which means that
as is the last part of the qualified name,
Import is a totally different kind of beast. We use it to call the Macro code. Elixir macro code is code that generates elixir code in compile time.
We tried to call
Integer.is_even function and got an error that we need to
We tried to be smart and use
alias, but that did not help.
import instead of
import we managed to call
is_even with a fully qualified name and without it. This is the difference between
As compiling macros could take time, we could use
import only. 1 is
The kernel is a macro module that is imported automatically. Why? Check the Kernel documentation, and you will figure out that if the statement is not a keyword but a macro function.
aliasis used for none Macro code
importis used for Macro’s
- What is Macro
- The kernel module is automatically imported because it represents the Elixir default environment.