import, alias, require, use in Elixir
| Import functions | |
| Short names | |
| Macros need require | |
| Use injects code |
Import functions
Import pulls named functions of another module into the current one, so you can call them without the module prefix. Keep the list small with the only option, because a wide import hides where each function comes from.
defmodule Greeter do
import String, only: [upcase: 1]
def shout(name) do
upcase(name)
end
end
Here only upcase with one argument joins Greeter, and every other String function still needs the String prefix. Prefer import for tiny helper sets and keep Enum style calls prefixed so readers see the source at once.
Short names
Alias shortens a module name without importing any functions. It is the common cure for long dotted paths that appear many times in one file.
defmodule Report do
alias Enum, as: E
def total(list) do
E.sum(list)
end
end
After the alias line, E.sum means Enum.sum, which stays clear because the short name still shows a module prefix. Many teams skip playful one letter names in large files and alias only the last segment instead.
Macros need require
Macros run at compile time, so the compiler must load the defining module before it can expand them. That loading step is require, and calling a macro without it raises a compile error.
defmodule Checker do
require Integer
def even?(n) do
Integer.is_even(n)
end
end
Integer.is_even is a macro that also works inside guards, which plain functions cannot do. Remember the rule of thumb: import is for functions, require is for macros.
Use injects code
Use calls a special macro named __using__ in the given module, and that macro injects code into the caller. Libraries rely on it to set up callbacks, imports, and default options in one line.
defmodule Hello do
defmacro __using__(_opts) do
quote do
def hello do
"hello"
end
end
end
end
Any module that writes use Hello receives its own hello function returning a greeting string.
defmodule Greeter do
use Hello
end
You will meet use again with test helpers and OTP behaviours, where one line wires up a whole set of defaults.
Next: Structs in Elixir
Article author: Arthur Isaev