Imports And Aliases In Elixir

TL;DR

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.

Alias

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 alias.

We first run position function with a fully qualified Elixir name.

Then we used alias syntax to rename is to our preferred name, CroBa.

Finally, we used alias without as which means that as is the last part of the qualified name, Basketball.

Import

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 require Integer.

We tried to be smart and use alias, but that did not help.

We used import instead of require.

With import we managed to call is_even with a fully qualified name and without it. This is the difference between require and import.

As compiling macros could take time, we could use import only. 1 is is_even arity.

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.

Remember

  • alias syntax
  • alias is used for none Macro code
  • import syntax
  • import is used for Macro’s
  • What is Macro
  • The kernel module is automatically imported because it represents the Elixir default environment.

Originally published at https://blog.tentamen.eu on June 17, 2020.

Founder of Tentamen, software testing agency.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store