Elixir: Require, Use, Alias and Import
Elixir allows special permissions to rename and use functions and macros in a variety of circumstances, using the keywords Alias, Use, Import and Require. Each have a specific meaning and purpose.
Alias
Alias allows you to rename, and therefore shorten, module names using an alternative. One can then call the functions of the original module using its alias, like so:
Use
Use allows you to use functions from a different module in your current module. Set up a macro defined as __using__
like this:
_Then call the module being used with use
keyword in the new module like so:
One can call the used module’s functions (if they are within the __using__
macro) in the new module.
Import
Allows you to select specific, or even use all, functions from a module, without having to use their module name as a prefix for the function. For instance, if we wanted to use Enum
’s count
function, we need to use the module name to define the function, otherwise we get a compiling error:
But using Import
:
To select specific functions we can name them like so:
Require
Require supplies us with macros that are executed and expanded at run-time - “code that generates code”. These kinds of macros are only available through use of the require
keyword. require
is only applicable for these macros, for instance we only need require
a module if we want to use its macros, it is not needed for its functions. An example is the .is_odd()
macro from the Integer
module: