Kernel.SpecialForms.alias
alias
, go back to Kernel.SpecialForms module for more information.
alias/2
is used to set up aliases, often useful with modules' names.
Examples
alias/2
can be used to set up an alias for any module:
defmodule Math do
alias MyKeyword, as: Keyword
end
In the example above, we have set up MyKeyword
to be aliased
as Keyword
. So now, any reference to Keyword
will be
automatically replaced by MyKeyword
.
In case one wants to access the original Keyword
, it can be done
by accessing Elixir
:
Keyword.values #=> uses MyKeyword.values
Elixir.Keyword.values #=> uses Keyword.values
Note that calling alias
without the :as
option automatically
sets an alias based on the last part of the module. For example:
alias Foo.Bar.Baz
Is the same as:
alias Foo.Bar.Baz, as: Baz
We can also alias multiple modules in one line:
alias Foo.{Bar, Baz, Biz}
Is the same as:
alias Foo.Bar
alias Foo.Baz
alias Foo.Biz
Lexical scope
import/2
, require/2
and alias/2
are called directives and all
have lexical scope. This means you can set up aliases inside
specific functions and it won't affect the overall scope.
Warnings
If you alias a module and you don't use the alias, Elixir is going to issue a warning implying the alias is not being used.
In case the alias is generated automatically by a macro, Elixir won't emit any warnings though, since the alias was not explicitly defined.
Both warning behaviours could be changed by explicitly
setting the :warn
option to true
or false
.