Elixir Aliases and Imports
An alias is a short name for a module. Import brings selected functions from a module into a script so they can be called without the module name.
An alias shortens a module call
The module Shop.Orders has a total function. The alias lets the call use Orders alone.
defmodule Shop.Orders do
def total(prices), do: Enum.sum(prices)
end
alias Shop.Orders
IO.puts(Orders.total([10, 15, 5]))Import makes map an unqualified call
The import brings in only Enum.map with two arguments. The call below writes map with no module name.
import Enum, only: [map: 2]
IO.inspect(map([200, 300], fn x -> x + 1 end))Two aliases can sit side by side
Each alias shortens one module name. Both shortened names work in the same script.
defmodule Shop.Orders do
def total(prices), do: Enum.sum(prices)
end
defmodule Shop.Gifts do
def wrap_fee(count), do: count * 2
end
alias Shop.Orders
alias Shop.Gifts
IO.puts(Orders.total([10, 20]))
IO.puts(Gifts.wrap_fee(4))Example
defmodule Shop.Orders do
def total(prices), do: Enum.sum(prices)
def biggest(prices), do: Enum.max(prices)
end
alias Shop.Orders
import Enum, only: [map: 2]
doubled = map([150, 200], fn x -> x * 2 end)
IO.inspect(doubled)
IO.puts(Orders.total(doubled))
IO.puts(Orders.biggest(doubled))Key points
- Alias: alias Shop.Orders lets the rest of a script call that module Orders.
- Full name: without an alias, every call must spell out the full name Shop.Orders.
- Rename: alias Shop.Orders, as: MyOrders calls the same module MyOrders instead.
- Import: import brings a module's functions in so a call needs no module name.
- Only: import Enum, only: [map: 2] imports just the map function that takes two arguments.
- Require: require names a module so its macros can be used, and this lesson uses no macros.
In this example, the script defines Shop.Orders with total and biggest functions. It aliases the module to Orders and imports only Enum.map with two arguments. It doubles each price with the unqualified map call, then prints the doubled list, its total, and its biggest value.
Note
alias and import change only the names in the script, never the modules themselves.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
After alias Shop.Orders, which call uses the alias correctly?