Imports And Aliases In Elixir

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post

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.

Image for post
Image for post

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

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

Written by

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